Can I suppress exceptions in a catch method when using IOC unity?
We would like to remove redundant try catch blocks in our application.
Obviously, a single interceptor can implement a regular handler and save a lot of duplicate code.
But I havent found a way to suppress the exception in the catch method.
Current:
void InterceptedMethod
{
try
{
}
catch()
{
}
}
Purpose:
void InterceptedMethod
{
//no try catch blocks
}
for example (using StreamReader sr = new StreamReader (invalid path)) will throw an exception in the catch method, which will not be caught if I remove the existing try catch block.
The code after (result.Exception! = Null) succeeds.
But it is currently only used for pre-entry and post-exit scripts.
I still need to remove the catch try blocks in the catch method. I know postharp or windsor Castle allows you to set properties.
What's the way with IOC unity?
source to share
For simple cases, it is relatively easy to create IInterceptionBehavior
one that will swallow exceptions. For example:
public class SuppressExceptionBehavior : IInterceptionBehavior
{
public IEnumerable<Type> GetRequiredInterfaces() => new Type[0];
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
IMethodReturn result = getNext()(input, getNext);
if (result.Exception != null)
{
result.Exception = null;
}
return result;
}
public bool WillExecute => true;
}
In the above example, if the method call returns an exception, it is null, which causes the exception to be swallowed.
The container can be configured as follows:
var container = new UnityContainer();
container.AddNewExtension<Interception>();
container.RegisterType<ITenantStore, TenantStore>(
new InterceptionBehavior<SuppressExceptionBehavior>(),
new Interceptor<InterfaceInterceptor>());
This works well for simple methods, such as those you mentioned: void InterceptedMethod() { }
. However, for the general case, you will have to analyze the expected return values to ensure that the correct types can be returned (or an exception will be thrown).
For example, what if the method has a return value? Now you need to set the object to result.ReturnValue
be a value compatible with the expected return type (or use input.CreateMethodReturn () with a valid value). For reference types it can be null, so it should work without any changes, but for value types (like int) it will need to be set to a specific value. Another example that will need to be handled (to avoid throwing an exception) is setting a default value for parameters.
source to share