jaimegildesagredo/finch — pull request #10 by paulmelnikow (2014-09-30 01:07:33+00:00)
Title: Allow subclasses to customize error handling

Hi Jaime,

I'm returning to some code I wrote last year based on Finch and Booby. My code is synchronous, so I basically forked Finch and modified it to suit my purposes. Thanks again for the great libraries; these APIs are really a pleasure to work with.

I offer this suggestion for Finch, based on a pattern that I found quite useful when building a synchronous API client. I suppose my goal is to make the API as similar to yours as possible, and offer programmers an architecture that lets them express the APIs as clearly as possible.

This changeset allows a collection to add semantic error handling which is specific to the API. For example, when a requested entity is not found, an API may return a 404 error with a specific message in the response content. Not all 404's are created equally, however: the API may also return a 404 if the endpoint doesn't exist. So rather than expect the caller to parse and handle the HTTP error object, it's useful to give the collection a chance to do so – and to return a more meaningful error object.

```py
class NotFound(object):
def __init__(self, message):
self.message = message

def on_error(self, callback, response):
if response.code == httplib.NOT_FOUND and escape.json_decode(response.body) == {'message': 'Could not find resource'}:
callback(NotFound('Could not find resource'))
else:
super(self, Collection).on_error(callback, response)
```

This also allows a collection to log failed requests. For example:

```py
def on_error(self, callback, response):
import logging
logger = logging.getLogger('my_api_client')
logger.error(response.body)
callback(errors.HTTPError(response.code))
```