Monday, September 8, 2008

Building an exception based API

Building an exception based API is useful for several reasons. One benefit I'm going to discuss here is the ability to model your system as a mesh of signals, or events. When dealing with exceptions, most people tend to lean toward using signal in the terminology. I, however, don't which term is used. The goal of creating an exception based API is to move away from the traditional synchronous invocation. Using events or signals achieves this.

I'm going to move out of the problem space here for a moment and into the solution space. In a programming language, when an exception is raised by some function or method, the normal flow of control is interrupted. I most cases, this is caused by a more primitive error such as in index error or name error. The flow of control then propagates outward, toward the highest level in the code. Along the way, there may be exception handlers. There are specialized code blocks that will execute if the appropriate exception is raised will the code in the context of the exception handler is executed.

The idea I'm trying to get across here is that exceptions can easily be modeled as signals. The code that raises the exception often has no idea if this exception will take place before the code is executed.

One approach to modeling an exception based API is to build a custom exception for the various flows of control. For example, we might model something like the following for a RESTful framework:


Here we have a Application object that represents application, or controller. The application object interacts directly with the Request object. The request object represents the request that is sent to our application from some client. Most web frameworks already support this abstraction out of the box. The remaining objects, GET, POST, PUT, and DELETE, are all modeled here as exceptions. Although there is no way to differentiate the regular objects from the exceptions, this is not the focus of this diagram. The focus here is to show how exceptions can be used as more than just exception handlers.

Another point to note, the sequence of messages dispatched from the Application object are not meant to represent the ordering of the message. It is meant to represent to potential messages that may be dispatched in response to a client request.

No comments :

Post a Comment