Skip to content

Commit

Permalink
App: add error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
jsmrcaga committed Mar 4, 2022
1 parent 9cb66b5 commit bf5fcbc
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
12 changes: 10 additions & 2 deletions lib/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,15 @@ 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');
}

this.router = router;
this.preprocessors = preprocessors;
this.postprocessors = postprocessors;
this.error_handler = null;
}

// Registers pre-processors
Expand Down Expand Up @@ -119,6 +120,10 @@ class App {
});
}

error(callback) {
this.error_handler = callback;
}

run(event) {
const { request } = event;
const { callback, params } = this.router.route(request);
Expand All @@ -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 });
});
}
Expand Down
30 changes: 30 additions & 0 deletions test/app/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));
});
});
});

0 comments on commit bf5fcbc

Please sign in to comment.