Get .NET MVC to completely ignore error - c#

I have a legacy library in my ASP.NET MVC app that raises a lot of exceptions I need to ignore. I ignore these exceptions in Application_Error like this
protected void Application_Error()
{
if (exception is PolicyViolationException)
{
Response.Clear();
Server.ClearError();
}
}
I know this is a code smell, but I can't do much about it at the moment.
Is there a way to stop them even getting to Application_Error?

Use a Wrapper class (the Adapter Pattern). Then, instead of referencing the legacy library, you use the wrapper class. And the wrapper can handle (or ignore) the exceptions as needed.
class Legacy
{ public void DoThis()
{ ... }
public void DoThat()
{ ... }
}
class Wrapper
{ Legacy _legacy;
public Wrapper() { _legacy = new Legacy(); }
public void DoThis()
{
try {
_legacy.DoThis();
}
catch (PolicyViolationException exception) {
//ignore
}
}
...
}
In this example, I would never reference the class Legacy. Instead, I would reference the class Wrapper. Then I don't have to worry about the exceptions because they won't get out of the Wrapper instance if I don't want them to.

Related

Catch an exception from an instance created with Activator.CreateInstance(type)

I have a C# application that can load other dlls with Activator.CreateInstance(type), that implement a given interface (plugins).
Now I want to catch all exceptions thrown from that new instance in it's own exception handler (because I cannot be sure that every exception is handled by the plugin properly) to present a message like:
Plugin [PluginName] caused the following error: [Exception.Message]
I can subscribe to the AppDomain.CurrentDomain.UnhandledException event, but this catches all exceptions and not only the ones caused by a certain plugin and I also can't see [that the|what] plugin caused the exception.
Is it possible to assign a exception handler to the created instance?
Thanks in advance,
Frank
I'm not sure I understand your exact scenario, but a solution could be creating a wrapper class around the plugin object that takes care of making sure all potential exceptions are handled correctly:
public interface IPluginObject
{
void Foo();
IBlah Bar();
...
}
public Wrapper<T>: IPluginObject where T: IPluginObject
{
private readonly T inner;
public Wrapper(IPlugin obj) { inner = obj; }
public void Foo()
{
try { inner.Foo() }
catch ....
finally ...
}
public IBlah Bar()
{
try { return inner.Bar(); }
catch ...
finally ...
}
}
Cumbersome? Yes, but you do get the benefit of knowing exactly what plugin is being troublesome.

How can i use simple aspect oriented concept to handle exception handling without postsharp?

i want to use AOP to handle my error exception in Console application. ( it is not MVC i used attribute vase programing to handle errors in mvc but this is console app) My code below: ( if error occurs ,it should throw an error yo my attribute side code )
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class HandleError : Attribute
{
public HandleError(string description)
{
try
{
this.Description = description;
}
catch (Exception)
{
throw;
}
}
public string Description { get; set; }
}
this will call from my method :
[HandleError("Error occurs here")]
public static void MyMethod(string data)
{
throw new Exception();
Actually; i want to use AOP to handle exceptions inside my method. i have to call attributes if it error occurs. But How? ( please don't offer postsharp, it needs money. but i am open for opensource also)By the way; why it is not easy ,i don't understand.
Basically, what PostSharp does is to weave code into your assembly at compile time that is run before and after the methods that are marked with the attributes. This is very good from a performance point of view because there is no use of code that is created dynamically at runtime.
Some other AOP frameworks (or IoC containers) offer the option to generate dynamic proxies that contain code that intercepts the calls to the methods at runtime.
Either you use one of those frameworks (look for IoC and interception) or you implement a comparable functionality by yourself. Basically what you have to do is to move the code you want to intercept into a class and mark the methods as virtual. At runtime, you decorate the instance of the class with a dynamically created class that inherits from your class and overrides the methods so that the additional code is run before and after the call to the method.
However, there might be a simpler approach that fits the needs of a console application. Instead of marking the methods with an attribute, you could also create some helper functions that contain the code that you want to run before and after the method:
void Main()
{
int value = GetValue(123);
DoSomething(value);
}
void DoSomething(int myParam)
{
RunAndLogError(() => {
// Place code here
Console.WriteLine(myParam);
});
}
int GetValue(int myParam)
{
return RunAndLogError(() => {
// Place code here
return myParam * 2;});
}
void RunAndLogError(Action act)
{
try
{
act();
}
catch(Exception ex)
{
// Log error
throw;
}
}
T RunAndLogError<T>(Func<T> fct)
{
try
{
return fct();
}
catch(Exception ex)
{
// Log error
throw;
}
}
As you can see, there are two overloads of RunAndLogError, one for void methods, the other one for methods that return a value.
Another option is to use a global exception handler for this purpose; see this answer for details: .NET Global exception handler in console application

How to properly write a custom UncaughtExceptionHandler in Xamarin.Android

All I want to achieve is to catch exceptions on my app so that I can send them to a server. I figured out that I can do this by writing my custom UncaughtExceptionHandler base on native Android code in Java answered here in StackOverflow.
This is my CustomExceptionHandler class:
public class CustomExceptionHandler : Thread.IUncaughtExceptionHandler
{
public IntPtr Handle { get; private set; }
public CustomExceptionHandler(Thread.IUncaughtExceptionHandler exceptionHandler)
{
Handle = exceptionHandler.Handle;
}
public void UncaughtException(Thread t, Throwable e)
{
// Submit exception details to a server
...
// Display error message for local debugging purposes
Debug.WriteLine(e);
}
public void Dispose()
{
throw new NotImplementedException();
}
}
Then I used this class to set the DefaultUncaughtExceptionHandler in my Activity:
// Set the default exception handler to a custom one
Thread.DefaultUncaughtExceptionHandler = new CustomExceptionHandler(
Thread.DefaultUncaughtExceptionHandler);
I don't know what is wrong with this approach, it did build but I got an InvalidCastException on runtime.
I have the same Thread.IUncaughtExceptionHandler interface types for my CustomExceptionHandler and the DefaultUncaughtExceptionHandler, but why am I getting this error? Please enlighten me. Thank you.
And it strikes again :D This is a common mistake. You have to inherit Java.Lang.Object if you implement Java interfaces.
public class CustomExceptionHandler : Java.Lang.Object, Thread.IUncaughtExceptionHandler
{
public void UncaughtException(Thread t, Throwable e)
{
// Submit exception details to a server
...
// Display error message for local debugging purposes
Debug.WriteLine(e);
}
}

C# AOP Custom attribute Unity

I'm trying to develop a custom attribute in order to decorate methods, and when I do that I want them to be "catched" by the attribute so it decides what to do with the exception.
I'm aware of specially two techniques to do this:
- PostSharp
- Enterprise Library Unity
I'd like to avoid the first one, I'd like to go ahead with Unity since we already use Enterprise Library.
So, in order to make this work, I've done the following:
My call handler:
public class LoggingCallHandler : ICallHandler
{
public bool Rethrow
{
get; set;
}
public bool Log
{
get; set;
}
public int Order
{
get; set;
}
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
var result = getNext().Invoke(input, getNext);
if (result.Exception != null)
{
if (this.Rethrow)
throw result.Exception;
if (this.Log)
this.LogException(result.Exception);
}
return result;
}
private void LogException(Exception ex)
{
// Do stuff
}
}
My custom attribute
public class LoggingCallHandlerAttribute : HandlerAttribute
{
private bool rethrow;
private bool log;
public LoggingCallHandlerAttribute(bool rethrow, bool log = false)
{
this.rethrow = rethrow;
this.log = log;
}
public override ICallHandler CreateHandler(IUnityContainer container)
{
return new LoggingCallHandler() { Rethrow = this.rethrow, Log = this.log };
}
}
My class with the method decorated with the attribute
public class TestManager
{
[LoggingCallHandler(false, false)]
public void DoStuff()
{
throw new Exception("TEST");
}
}
When I run the method, no AOP happens.
I'm aware thar Unity may rely or relies at all in containers. But we don't use any of that currently, so we'd like just to decorate a method with the [LoggingCallHandler] attribute and that's it.
If container is really necessary it can be considered but it would be nice to have a single container that fits all purposes (at least for now...).
Is it possible to achieve this?
Thank you guys.
I actively work on NConcern .NET AOP Framework a new open source project. You could try it to do what you need.
Aspect to manage your exception handling
public class ExceptionHandlingAspect : IAspect
{
private void Log(Exception exception)
{
//...
}
public IEnumerable<IAdvice> Advise(MethodInfo method)
{
//advise only if method is tagged.
if (Attribute.IsDefined(method, typeof(LoggingCallHandlerAttribute))
{
//get attribute
var attribute = method.GetCustomAttributes(typeof(LoggingCallHandlerAttribue))[0] as LoggingCallHandlerAttribute;
//describe how yo rewrite method.
yield return Advice.Basic.Arround(invoke =>
{
try { invoke(); } //call original code
catch (Exception e)
{
if (attribute.Rethrow)
{
throw;
}
if (attribute.Log)
{
this.Log(e);
}
}
});
}
}
}
attach aspect to all methods attributed with LoggingCallHandlerAttribute;
Aspect.Weave<ExceptionHandlingAspect>(method => method.IsDefined(typeof(LoggingCallHandlerAttribute), true);
If you don't use Unity container to construct your objects, then the interception (via ICallHandler) will not work.
Such interception depends on Unity to wrap your objects when you create them through the Unity DI container.
PostSharp interception will work even if you don't use a DI container.
If you don't use a DI container, (IMO) it might be better for you to keep things as is and don't introduce a DI container to your code base. See my article here.
You might also want to consider doing interception using DynamicProxy. But this requires you to wrap your objects manually when you create them.

Use ExceptionHelper class as an Attribute/Extension/Property for a Method/Class level in c#

Currently I have a Exception helper Class
public class ExceptionHelper
{
public static void Catch(Action action)
{
try
{
action();
}
catch (Exception ex)
{
// log error and thorw
// Do what you want
}
}
}
This is used to wrap methods in other classes to catch and logs exceptions like this
public static class RepoManger1
{
public static void TestMethod(string something)
{
ExceptionHelper.Catch(() =>
{
Int32 testvar1 = 10;
Int32 testvar2 = 0;
Int32 testvar3 = testvar1 / testvar2;
});
}
}
I am thinking of converting this to an Attribute that can be defined on a class or method
so that i do not have to write this code on every method.
Any other approach can also be suggested for the same
Attributes are meant to provide extra information about a class or method, while, if I understood correctly, you would like methods with your attribute to be automatically wrapped in your exception handling code, which is not possible.
In my opinion, the best thing to do here would be something like this:
public class ExceptionHelper {
public static void ProcessException(Exception exc) {
// common exception handling code
// e.g. log error, but DO NOT throw
}
}
public static class RepoManger1 {
public static void TestMethod(string something) {
try {
// do something
} catch (Exception exc) {
ExceptionHelper.ProcessException(exc);
// if necessary, re-throw the exception HERE, so that
// people reading your code can see that the exception
// is being re-thrown
throw;
}
}
}
I think that this is much more readable than your previous approach (and of any possible solution involving attributes). When I look at this code, I immediately understand that you are catching an exception and doing something with it, in the other cases it would take a while to figure it out.

Categories