I am building a .NET WebApi application and I would like to set up a global error handler (basically a function that executes when an exception bubbles up from anywhere in the application). this link laments support for this, but several workarounds are offered. Unfortunately, I can't seem to find useful documentation for any of them.
Here are my requirements:
How do I go about setting this up?
If you update to Web API v2.1, available via Nuget with this command:
Install-Package Microsoft.AspNet.WebApi
You can create a Global Exception Handler by inheriting from Exception Logger.
Here is an example:
class TraceExceptionLogger : ExceptionLogger
{
public override void LogCore(ExceptionLoggerContext context)
{
Trace.TraceError(context.ExceptionContext.Exception.ToString());
}
}
More details in the release notes here: http://www.asp.net/web-api/overview/releases/whats-new-in-aspnet-web-api-21#global-error
There are a few options you should be aware of:
Event AppDomain.CurrentDomain.FirstChanceException :
Will fire for every exception no matter if it is handled. Use this for logging etc before your specific handler.
Event AppDomain.CurrentDomain.UnhandledException :
Will Fire for every exception not handled in code
You would need to create handler in a service that has access to your IOC container etc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.