From f6a2f54aef50e2edc5ae0d54ffa7e4d38c72f66a Mon Sep 17 00:00:00 2001 From: TJ Holowaychuk Date: Tue, 27 Aug 2013 20:36:44 -0700 Subject: [PATCH] add error handling example --- examples/errors.js | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 examples/errors.js diff --git a/examples/errors.js b/examples/errors.js new file mode 100644 index 0000000..41f2442 --- /dev/null +++ b/examples/errors.js @@ -0,0 +1,42 @@ + +var http = require('http'); +var koa = require('..'); +var app = koa(); + +// look ma, error propagation! + +app.use(function(next){ + return function *(){ + try { + yield next; + } catch (err) { + // some errors will have .status + // however this is not a guarantee + this.status = err.status || 500; + this.type = 'html'; + this.body = '

Something exploded, please contact Maru.

'; + + // since we handled this manually we'll + // want to delegate to the regular app + // level error handling as well so that + // centralized still functions correctly. + this.app.emit('error', err); + } + } +}); + +// response + +app.use(function(next){ + return function *(){ + throw new Error('boom boom'); + } +}); + +// error handler + +app.on('error', function(err){ + console.log('sent error %s to the cloud', err.message); +}); + +app.listen(3000);