Handling WebAPI exceptions with Angular http interceptor

It’s good to return meaningful HTTP status codes upon server exceptions. Whether it be invalid model state, conflict upon trying to create/update an object in the database, unauthorized access or something else it adds additional value and sends a message – one that’s different from generic 400’s or 500’s. These messages can then be used to take certain kinds of actions on the client side based on what happened.

For example you could register a custom ApplicationExceptionHandler.cs inside your WebApiConfig.cs which would then be able to catch and handle any kind of exception thrown by lower server layers (such as business layer or the DB/ORM layer):

You need to register ApplicationExceptionHandler in WebApiConfig.cs like this:

You can also use something like ValidationFilter to take care of invalid model states in an easy way (by replying with a 422). After you have all your desired/needed exception handlers in place, it’s time to setup the client side. You can easily intercept every HTTP request and act upon responses from the server with an http request interceptor that looks like this:

Now you have a centralized way to handle all kinds of WebAPI errors. Simply build upon this infrastructure and add whatever else you might need. In one of the future posts I’ll explain how to create basic html input element directives (for text, textarea, number, datetime and similar fields) which also seamlessly take care of modelState error messages by presenting them to the user just below the input element.