Global Error Handling in ASP.NET Web API 2
by David Matson, Rick Anderson
Today there’s no easy way in Web API to log or handle errors globally. Some unhandled exceptions can be processed via exception filters, but there are a number of cases that exception filters can’t handle. For example:
- Exceptions thrown from controller constructors.
- Exceptions thrown from message handlers.
- Exceptions thrown during routing.
- Exceptions thrown during response content serialization .
We want to provide a simple, consistent way to log and handle (where possible) these exceptions.
There are two major cases for handling exceptions, the case where we are able to send an error response and the case where all we can do is log the exception. An example for the latter case is when an exception is thrown in the middle of streaming response content; in that case it is too late to send a new response message since the status code, headers, and partial content have already gone across the wire, so we simply abort the connection. Even though the exception can’t be handled to produce a new response message, we still support logging the exception. In cases where we can detect an error, we can return an appropriate error response as shown in the following:
[!code-csharpMain]
1: public IHttpActionResult GetProduct(int id)
2: {
3: var product = products.FirstOrDefault((p) => p.Id == id);
4: if (product == null)
5: {
6: return NotFound();
7: }
8: return Ok(product);
9: }
Existing Options
In addition to exception filters, message handlers can be used today to observe all 500-level responses, but acting on those responses is difficult, as they lack context about the original error. Message handlers also have some of the same limitations as exception filters regarding the cases they can handle.While Web API does have tracing infrastructure that captures error conditions the tracing infrastructure is for diagnostics purposes and is not designed or suited for running in production environments. Global exception handling and logging should be services that can run during production and be plugged into existing monitoring solutions (for example, ELMAH ).
Solution Overview
We provide two new user-replaceable services, IExceptionLogger and IExceptionHandler, to log and handle unhandled exceptions. The services are very similar, with two main differences:
- We support registering multiple exception loggers but only a single exception handler.
- Exception loggers always get called, even if we’re about to abort the connection. Exception handlers only get called when we’re still able to choose which response message to send.
Both services provide access to an exception context containing relevant information from the point where the exception was detected, particularly the HttpRequestMessage, the HttpRequestContext, the thrown exception and the exception source (details below).
Design Principles
- No breaking changes Because this functionality is being added in a minor release, one important constraint impacting the solution is that there be no breaking changes, either to type contracts or to behavior. This constraint ruled out some cleanup we would like to have done in terms of existing catch blocks turning exceptions into 500 responses. This additional cleanup is something we might consider for a subsequent major release. If this is important to you please vote on it at ASP.NET Web API user voice.
- Maintaining consistency with Web API constructs Web API’s filter pipeline is a great way to handle cross-cutting concerns with the flexibility of applying the logic at an action-specific, controller-specific or global scope. Filters, including exception filters, always have action and controller contexts, even when registered at the global scope. That contract makes sense for filters, but it means that exception filters, even globally scoped ones, aren’t a good fit for some exception handling cases, such as exceptions from message handlers, where no action or controller context exists. If we want to use the flexible scoping afforded by filters for exception handling, we still need exception filters. But if we need to handle exception outside of a controller context, we also need a separate construct for full global error handling (something without the controller context and action context constraints).
When to Use
- Exception loggers are the solution to seeing all unhandled exception caught by Web API.
- Exception handlers are the solution for customizing all possible responses to unhandled exceptions caught by Web API.
- Exception filters are the easiest solution for processing the subset unhandled exceptions related to a specific action or controller.
Service Details
The exception logger and handler service interfaces are simple async methods taking the respective contexts:
[!code-csharpMain]
1: public interface IExceptionLogger
2: {
3: Task LogAsync(ExceptionLoggerContext context,
4: CancellationToken cancellationToken);
5: }
6:
7: public interface IExceptionHandler
8: {
9: Task HandleAsync(ExceptionHandlerContext context,
10: CancellationToken cancellationToken);
11: }
We also provide base classes for both of these interfaces. Overriding the core (sync or async) methods is all that is required to log or handle at the recommended times. For logging, the ExceptionLogger
base class will ensure that the core logging method is only called once for each exception (even if it later propagates further up the call stack and is caught again). The ExceptionHandler
base class will call the core handling method only for exceptions at the top of the call stack, ignoring legacy nested catch blocks. (Simplified versions of these base classes are in the appendix below.) Both IExceptionLogger
and IExceptionHandler
receive information about the exception via an ExceptionContext
.
[!code-csharpMain]
1: public class ExceptionContext
2: {
3: public Exception Exception { get; set; }
4:
5: public HttpRequestMessage Request { get; set; }
6:
7: public HttpRequestContext RequestContext { get; set; }
8:
9: public HttpControllerContext ControllerContext { get; set; }
10:
11: public HttpActionContext ActionContext { get; set; }
12:
13: public HttpResponseMessage Response { get; set; }
14:
15: public string CatchBlock { get; set; }
16:
17: public bool IsTopLevelCatchBlock { get; set; }
18: }
When the framework calls an exception logger or an exception handler, it will always provide an Exception
and a Request
. Except for unit testing, it will also always provide a RequestContext
. It will rarely provide a ControllerContext
and ActionContext
(only when calling from the catch block for exception filters). It will very rarely provide a Response
(only in certain IIS cases when in the middle of trying to write the response). Note that because some of these properties may be null
it is up to the consumer to check for null
before accessing members of the exception class.CatchBlock
is a string indicating which catch block saw the exception. The catch block strings are as follows:
- HttpServer (SendAsync method)
- HttpControllerDispatcher (SendAsync method)
- HttpBatchHandler (SendAsync method)
- IExceptionFilter (ApiController’s processing of the exception filter pipeline in ExecuteAsync)
OWIN host:
- HttpMessageHandlerAdapter.BufferResponseContentAsync (for buffering output)
- HttpMessageHandlerAdapter.CopyResponseContentAsync (for streaming output)
Web host:
- HttpControllerHandler.WriteBufferedResponseContentAsync (for buffering output)
- HttpControllerHandler.WriteStreamedResponseContentAsync (for streaming output)
- HttpControllerHandler.WriteErrorResponseContentAsync (for failures in error recovery under buffered output mode)
The list of catch block strings is also available via static readonly properties. (The core catch block string are on the static ExceptionCatchBlocks; the remainder appear on one static class each for OWIN and web host).IsTopLevelCatchBlock
is helpful for following the recommended pattern of handling exceptions only at the top of the call stack. Rather than turning exceptions into 500 responses anywhere a nested catch block occurs, an exception handler can let exceptions propagate until they are about to be seen by the host.
In addition to the ExceptionContext
, a logger gets one more piece of information via the full ExceptionLoggerContext
:
[!code-csharpMain]
1: public class ExceptionLoggerContext
2: {
3: public ExceptionContext ExceptionContext { get; set; }
4: public bool CanBeHandled { get; set; }
5: }
The second property, CanBeHandled
, allows a logger to identify an exception that cannot be handled. When the connection is about to be aborted and no new response message can be sent, the loggers will be called but the handler will not be called, and the loggers can identify this scenario from this property.
In additional to the ExceptionContext
, a handler gets one more property it can set on the full ExceptionHandlerContext
to handle the exception:
[!code-csharpMain]
1: public class ExceptionHandlerContext
2: {
3: public ExceptionContext ExceptionContext { get; set; }
4: public IHttpActionResult Result { get; set; }
5: }
An exception handler indicates that it has handled an exception by setting the Result
property to an action result (for example, an ExceptionResult, InternalServerErrorResult, StatusCodeResult, or a custom result). If the Result
property is null, the exception is unhandled and the original exception will be re-thrown.
For exceptions at the top of the call stack, we took an extra step to ensure the response is appropriate for API callers. If the exception propagates up to the host, the caller would see the yellow screen of death or some other host provided response which is typically HTML and not usually an appropriate API error response. In these cases, the Result starts out non-null, and only if a custom exception handler explicitly sets it back to null
(unhandled) will the exception propagate to the host. Setting Result
to null
in such cases can be useful for two scenarios:
- OWIN hosted Web API with custom exception handling middleware registered before/outside Web API.
- Local debugging via a browser, where the yellow screen of death is actually a helpful response for an unhandled exception.
For both exception loggers and exception handlers, we don’t do anything to recover if the logger or handler itself throws an exception. (Other than letting the exception propagate, leave feedback at the bottom of this page if you have a better approach.) The contract for exception loggers and handlers is that they should not let exceptions propagate up to their callers; otherwise, the exception will just propagate, often all the way to the host resulting in an HTML error (like the ASP.NET’s yellow screen) being sent back to the client (which usually isn’t the preferred option for API callers that expect JSON or XML).
Examples
Tracing Exception Logger
The exception logger below send exception data to configured Trace sources (including the Debug output window in Visual Studio).
[!code-csharpMain]
1: class TraceExceptionLogger : ExceptionLogger
2: {
3: public override void LogCore(ExceptionLoggerContext context)
4: {
5: Trace.TraceError(context.ExceptionContext.Exception.ToString());
6: }
7: }
Custom Error Message Exception Handler
The following below produces a custom error response to clients, including an email address for contacting support.
[!code-csharpMain]
1: class OopsExceptionHandler : ExceptionHandler
2: {
3: public override void HandleCore(ExceptionHandlerContext context)
4: {
5: context.Result = new TextPlainErrorResult
6: {
7: Request = context.ExceptionContext.Request,
8: Content = "Oops! Sorry! Something went wrong." +
9: "Please contact support@contoso.com so we can try to fix it."
10: };
11: }
12:
13: private class TextPlainErrorResult : IHttpActionResult
14: {
15: public HttpRequestMessage Request { get; set; }
16:
17: public string Content { get; set; }
18:
19: public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
20: {
21: HttpResponseMessage response =
22: new HttpResponseMessage(HttpStatusCode.InternalServerError);
23: response.Content = new StringContent(Content);
24: response.RequestMessage = Request;
25: return Task.FromResult(response);
26: }
27: }
28: }
Registering Exception Filters
If you use the “ASP.NET MVC 4 Web Application” project template to create your project, put your Web API configuration code inside the WebApiConfig
class, in the *App/_Start* folder:
[!code-csharpMain]
1: public static class WebApiConfig
2: {
3: public static void Register(HttpConfiguration config)
4: {
5: config.Filters.Add(new ProductStore.NotImplExceptionFilterAttribute());
6:
7: // Other configuration code...
8: }
9: }
Appendix: Base Class Details
[!code-csharpMain]
1: public class ExceptionLogger : IExceptionLogger
2: {
3: public virtual Task LogAsync(ExceptionLoggerContext context,
4: CancellationToken cancellationToken)
5: {
6: if (!ShouldLog(context))
7: {
8: return Task.FromResult(0);
9: }
10:
11: return LogAsyncCore(context, cancellationToken);
12: }
13:
14: public virtual Task LogAsyncCore(ExceptionLoggerContext context,
15: CancellationToken cancellationToken)
16: {
17: LogCore(context);
18: return Task.FromResult(0);
19: }
20:
21: public virtual void LogCore(ExceptionLoggerContext context)
22: {
23: }
24:
25: public virtual bool ShouldLog(ExceptionLoggerContext context)
26: {
27: IDictionary exceptionData = context.ExceptionContext.Exception.Data;
28:
29: if (!exceptionData.Contains("MS_LoggedBy"))
30: {
31: exceptionData.Add("MS_LoggedBy", new List<object>());
32: }
33:
34: ICollection<object> loggedBy = ((ICollection<object>)exceptionData[LoggedByKey]);
35:
36: if (!loggedBy.Contains(this))
37: {
38: loggedBy.Add(this);
39: return true;
40: }
41: else
42: {
43: return false;
44: }
45: }
46: }
47:
48: public class ExceptionHandler : IExceptionHandler
49: {
50: public virtual Task HandleAsync(ExceptionHandlerContext context,
51: CancellationToken cancellationToken)
52: {
53: if (!ShouldHandle(context))
54: {
55: return Task.FromResult(0);
56: }
57:
58: return HandleAsyncCore(context, cancellationToken);
59: }
60:
61: public virtual Task HandleAsyncCore(ExceptionHandlerContext context,
62: CancellationToken cancellationToken)
63: {
64: HandleCore(context);
65: return Task.FromResult(0);
66: }
67:
68: public virtual void HandleCore(ExceptionHandlerContext context)
69: {
70: }
71:
72: public virtual bool ShouldHandle(ExceptionHandlerContext context)
73: {
74: return context.ExceptionContext.IsOutermostCatchBlock;
75: }
76: }
|