Is it possible to use source generators to handle exceptions?

Viewed 56

I have an interface:

Task DoStuff();

And an implementation:

public async Task DoStuff()
{
    await DoStuffAndThrowException();
}

Is there a way to use source code generators in order to handle exceptions for example like:

public async Task DoStuff()
{
    try
    {
        await DoStuffAndThrowException();
    }
    catch (Exception exception)
    {
        throw new MySpecialException(exception);
    }
}

or:

public async Task DoStuff()
{
    await DoStuffAndThrowExceptionWrapped();
}

public async Task DoStuffAndThrowExceptionWrapped()
{
    try
    {
        await DoStuffAndThrowException();
    }
    catch (Exception exception)
    {
        throw new MySpecialException(exception);
    }
}
1 Answers

I'm not an expert on Source Generators, but from what I've understood they don't modify existing methods: they're meant to add generated source. So they're good for the kinds of things you might put in a separate partial class file.

What you're looking to do would be better accomplished by an aspect-oriented programming framework. Postsharp is made for these kinds of things, but it costs money and I haven't used it. There are some free plugins for the Fody Weaver library that can probably help you do what you're looking for. For example, MethodBoundaryAspect.Fody will let you create an attribute that alters the behaviors of method entry, exit, and exceptions, and then you can apply those attributes on specific methods, all methods in a class, or all methods in an assembly.

Related