You are here

How To Bubble System Exceptions into Your API’s HTTP Response Codes

When creating Web APIs, it is important to have a plan in place for dealing with any errors that may occur. While opinions on how to go about this may vary depending on who you speak to, this tutorial by Michael Lumpp on the Karbyn Blog uses exception filters and exception handlers to allow system exceptions to bubble up to the top of the stack, where they can be dealt with.

A typical exception event occurs when there is a hardware or software error, such as a hard disk crash or an attempt to access an out-of-bounds array element. Information about the exception and the conditions it occurred in are recorded as the runtime system “throws an exception”.

The system then searches backwards through the call stack looking for an appropriate exception handler for that particular type of exception. This movement through the call stack is known as exception bubbling, which ends with an event handler “catching the exception”, and executing the predefined action.

The author begins this tutorial by discussing exception filters and placing a breakpoint within the class that initiates a specified action. The attribute can then be edited to gain control over the HTTP response code that is returned to add a customised error message.

The author then describes exception handlers and how to use these to catch unhandled exceptions thrown by the exception filters. You can specify an appropriate action to take and apply your customised response code.

This tutorial looks at the problem from a .NET point of view, but the concepts ar­e easily transferrable to other platforms. Sample code is provided with notes on working within Visual Studio to create the Web API project from scratch.

Be sure to read the next API Design article: How Instagram Tied its Infrastructure to Apple’s 3D Touch API

Original Article

Handling Errors in Web API Using Exception Filters and Exception Handlers

 

Comments