Skip to content

Commit

Permalink
Add support for headers in errors
Browse files Browse the repository at this point in the history
  • Loading branch information
PlasmaPower committed Mar 1, 2016
1 parent 93c356a commit 36119c2
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 1 deletion.
38 changes: 38 additions & 0 deletions docs/error-handling.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Error Handling

## Try-Catch

Using generators means that you can try-catch `next`. For example,
this example prepends all error messages with "Error: "

```js
app.use(function*(next){
try {
yield next;
} catch (error) {
error.message = 'Error: ' + error.message;
throw error;
}
});
```

## The Error Event

Error handlers can be specified with `app.on('error')`.
If no error handler is specified, a default error handler
is used. Error handlers recieve all errors that make their
way back through the middleware chain, if an error is caught
and not thrown again, it will not be handled by the error
handler.

### The Default Error Event Handler

The default error handler is a good error handler for most
use cases. It will use a status code of `err.status`, or by
default 500. If `err.expose` is truthy, then `err.message`
will be the reply. Otherwise, a message generated from the
error code will be used (e.g. for the code 500 the message
"Internal Server Error" will be used). All headers will be
cleared from the request, but any headers in `err.headers`
will then be set. You can use a try-catch, as specified
above, to add a header to this list.
3 changes: 2 additions & 1 deletion lib/context.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,9 @@ var proto = module.exports = {
return;
}

// unset all headers
// unset all headers, and set those specified
this.res._headers = {};
this.set(err.headers);

// force text/plain
this.type = 'text';
Expand Down
34 changes: 34 additions & 0 deletions test/context/onerror.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,40 @@ describe('ctx.onerror(err)', function(){
})
})

it('should keep headers specified in the error', function(done){
var app = koa();

app.use(function *(next){
this.set('Vary', 'Accept-Encoding');
this.set('X-CSRF-Token', 'asdf');
this.body = 'response';

throw Object.assign(new Error('boom'), {
status: 418,
expose: true,
headers: {
'X-New-Header': 'Value'
}
})
})

var server = app.listen();

request(server)
.get('/')
.expect(418)
.expect('Content-Type', 'text/plain; charset=utf-8')
.expect('X-New-Header', 'Value')
.end(function(err, res){
if (err) return done(err);

res.headers.should.not.have.property('vary');
res.headers.should.not.have.property('x-csrf-token');

done();
})
})

describe('when invalid err.status', function(){
describe('not number', function(){
it('should respond 500', function(done){
Expand Down

0 comments on commit 36119c2

Please sign in to comment.