diff --git a/lib/app.js b/lib/app.js index 83fb426..7181ca7 100644 --- a/lib/app.js +++ b/lib/app.js @@ -17,7 +17,7 @@ const CORS = ({ origin='*', methods='HEAD,PUT,DELETE,POST,GET,OPTIONS', max_age= class App { static CORS = CORS; - constructor(router, preprocessors=[], postprocessors=[]) { + constructor(router, preprocessors=[], postprocessors=[], error_handler=null) { if(!router) { throw new Error('Please instanciate app with a root router'); } @@ -25,6 +25,7 @@ class App { this.router = router; this.preprocessors = preprocessors; this.postprocessors = postprocessors; + this.error_handler = null; } // Registers pre-processors @@ -119,6 +120,10 @@ class App { }); } + error(callback) { + this.error_handler = callback; + } + run(event) { const { request } = event; const { callback, params } = this.router.route(request); @@ -134,7 +139,10 @@ class App { return this.postprocess(response, request, params, event); }).catch(e => { // Handle 500 - console.error(e); + if(this.error_handler) { + return this.error_handler(e, request, params, event); + } + return new Response(null, { status: 500 }); }); } diff --git a/test/app/app.js b/test/app/app.js index af49cf7..864c497 100644 --- a/test/app/app.js +++ b/test/app/app.js @@ -228,4 +228,34 @@ describe('App', () => { done(); }).catch(e => done(e)); }); + + describe('Error handling', () => { + it('Should register an error handler and call it', done => { + const router = new Router(); + + router.get('/plep/:plop', () => { + throw new Error('Simulated error'); + }); + + const app = new App(router); + + app.error((err, request, params, event) => { + return new Response('test', { + status: 505 + }); + }); + + app.run({ + request: { + url: 'https://google.com/plep/5', + method: 'GET' + } + }).then(result => { + expect(result).to.be.instanceof(Response); + expect(result.status).to.be.eql(505); + expect(result.body).to.be.eql('test'); + done(); + }).catch(e => done(e)); + }); + }); });