Web API 2.1 brings a lot of great new features to the table. One of them is global error handling, allowing you to log all unhandled exceptions through one central mechanism
This is a sample from the Web Api documentation:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TraceSourceExceptionLogger : ExceptionLogger | |
{ | |
private readonly TraceSource _traceSource; | |
public TraceSourceExceptionLogger(TraceSource traceSource) | |
{ | |
_traceSource = traceSource; | |
} | |
public override void Log(ExceptionLoggerContext context) | |
{ | |
_traceSource.TraceEvent(TraceEventType.Error, 1, | |
"Unhandled exception processing {0} for {1}: {2}", | |
context.Request.Method, | |
context.Request.RequestUri, | |
context.Exception); | |
} | |
} | |
config.Services.Add(typeof(IExceptionLogger), | |
new TraceSourceExceptionLogger(new | |
TraceSource("MyTraceSource", SourceLevels.All))); |
The annoying thing I noticed is that the IExceptionLogger interface is not resolved through the dependency injection integration mechanism that Web API offers out-of-the-box. So you explicitly have to register your implementation through the Services property on the HttpConfiguration object.
Hopefully the Web API team will change this in the future...