Tuesday, June 19, 2012

ASP.Net Web API and Exception Shielding

Exception shielding (or exception sanitation) is a integration pattern that should always be implemented to ensure unexpected exceptions never arrive at the client (a.k.a bleed through). 

For MVC 4's Web Api - this is achieved by overriding the OnException method, on the ExceptionFilterAttribute class. Here you can inspect the exception that was thrown, and sanitise if required (change the exception to be more generic). 

However, the mechanism to return http status codes - e.g. 404 - when a resource is not found, is to throw an HttpResponsException with the appropriate status code. This ensures that RESTful semantics are upheld. 

During development, I updated the OnException method to ignore exceptions of type HttpResponsException, as these are intended to reach the client. However the method was never invoked. After some googling, I discovered the filter is smart enough to know that HttpResponseExceptions should be ignored - "An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception. TheHttpResponseException type is a special case, because it is designed specifically for returning an HTTP response."

9 comments: