-
Notifications
You must be signed in to change notification settings - Fork 7
Error Handling
Brick.JS catch errors from REST routers exactly like Express.js,
including next(err) and throw err (not for async).
This article explains:
- How to throw an Error,
- How to set HTTP status code when error occurred, and
- How to customize the error page.
To do this, you can simply throw an error within any of the REST routers:
exports.post = function(req, res, next){
throw(new Error('some bad thing happened'));
};While next(err) should be called if Errors are generated asynchronously:
exports.post = function(req, res, next){
Promise.resolve(sth)
.then(x => res.render(x))
.catch(next);
};In order to set HTTP status code, set Error.status before throw.
exports.post = function(req, res, next){
var e = new Error('some bad thing happened');
e.status = 400;
next(e);
};If no status set, Brick.JS will set status code to 500.
Brick.JS provides brick.expressCatch404 middleware for convenience.
Simply app.use(brick.expressCatch404) to enable this middleware.
Brick.JS does not provide error pages by default.
Errors passed to next will be handled by Express.js by default.
You can register an error brick to Brick.JS (after all middlewares):
// middlewares
app.use(brick.express);
app.use(brick.expressCatch404);
// error handler brick
app.use(brick.expressErrorHandler({
// register the brick called 'error' as an error handler brick.
brick: 'error'
});A typical error brick looks like:
router.js:
exports.get = function(req, res, next){
var err = res.locals.error;
console.error(err);
res
.status(err.status || 500)
.render({
message: err.message.toUpperCase(),
stack: err.stack
});
}
exports.getwill always be called regardless the entry METHOD of current HTTP request.
res.localsrefers to current context, see: REST Routers.
view.html:
<h2>{{message}}</h2>
<pre><code>{{stack}}</code></pre>You are free to include different Template partials according to err.status.
Copyright © 2016 Harttle