Skip to content
This repository was archived by the owner on Apr 14, 2026. It is now read-only.

Error Handling

Jun Yang edited this page Sep 12, 2016 · 10 revisions

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.

Throw an Error

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);
};

Status Code

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.

Catch 404

Brick.JS provides brick.expressCatch404 middleware for convenience. Simply app.use(brick.expressCatch404) to enable this middleware.

Customize Error Page

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.get will always be called regardless the entry METHOD of current HTTP request.

res.locals refers 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.

Clone this wiki locally