A C# Fody plugin that allows you to annotate a method with the [SwallowExceptions] attribute to have the method contents wrapped in a try / catch block.
SwallowExceptions package https://www.nuget.org/packages/SwallowExceptions.Fody
PM> Install-Package SwallowExceptions.Fody
public class MyClass
{
[SwallowExceptions]
void MyMethod()
{
DoSomethingDangerous();
}
}
public class MyClass
{
void MyMethod()
{
try
{
DoSomethingDangerous();
}
catch (Exception exception)
{
}
}
}
In the case of other attribute based Fody plugins, i.e. Anotar, the order that the plugins get invoked becomes important.
In most cases you'd like this plugin to be the last plugin to inject code into a method, to do so ensure that it is the last plugin listed in the project's FodyWeavers.xml file like shown here:
<?xml version="1.0" encoding="utf-8"?>
<Weavers>
<Anotar.Log4Net />
<SwallowExceptions />
</Weavers>
In this case, you can do things like the following, where Anotar will log the exception, then SwallowExceptions will catch the rethrown exception:
public class MyClass
{
[LogToFatalOnException, SwallowExceptions]
void MyMethod()
{
DoSomethingDangerous();
}
}
public class MyClass
{
void MyMethod()
{
try
{
try
{
DoSomethingDangerous();
}
catch (Exception exception)
{
if (logger.IsErrorEnabled)
{
var message = string.Format("Exception occurred in SimpleClass.MyMethod. param1 '{0}', param2 '{1}'", param1, param2);
logger.ErrorException(message, exception);
}
throw;
}
}
catch (Exception exception)
{
}
}
}
This is a simple solution used to illustrate how to write a Fody addin.
See also Fody usage.
Install the BasicFodyAddin.Fody NuGet package and update the Fody NuGet package:
PM> Install-Package Fody
PM> Install-Package BasicFodyAddin.Fody
The Install-Package Fody
is required since NuGet always defaults to the oldest, and most buggy, version of any dependency.
Add <BasicFodyAddin/>
to FodyWeavers.xml
<Weavers>
<BasicFodyAddin/>
</Weavers>
See writing an addin
Edit the value in the Version element of Directory.Build.props
Run the following command in ./SwallowExceptions/
dotnet pack .\SwallowExceptions.csproj -c Release
The NuGet package will be saved as ./nugets/SwallowExceptions.Fody.(VersionNumber).nupkg
Lego designed by Timur Zima from The Noun Project.