TxSSC/Card-Catalog — pull request #5 by particlebanana (2012-08-14 15:06:47+00:00)
Title: Before Middleware + Error Handling

**NOTE:** This includes the commits from the other pull request to make it all one clean package.

## Error Handling

This allows you to pass in an error handling function when the catalog is created.

All it does is catch an error event on the Category or Collection classes and run it through the error_handler function. It doesn't pass in the req object but if that becomes an issue it's easy to add.

```js
var catalog = new card_catalog.Category({
connection: connection,
namespace: 'example_namespace',
error_handler: function(res, err) {
// Do something with the error
}
});
```

## Before Middleware

This allows you to insert middleware functions at 2 points in the request lifecycle. You can have global functions that are filtered through before a request is passed off to the category router and functions that are attached to a card instance.

The functions at the global level should be things like a body parser, method override, etc. The functions on a card level should only be things that are related to request on that card.

### Global Middleware

```js
var catalog = new card_catalog.Category({
connection: connection,
namespace: 'example_namespace'
});

catalog.before = [
connect.bodyParser(),
connect.methodOverride()
];

// server function dispatch
http.createServer(function(req, res) {
catalog.dispatch(req, res);
});
```

### Card Level Before Functions

```js
var Example = module.exports = function Example(options) {
card_catalog.Card.call(options);

// Card name, slug, other options

this.before = [
// Connect style middleware
function(req, res, next) {
// some logic
next();
},

// Flatiron style middleware
function(req, res) {
// some logic
res.emit('next');
}
];
```