- 
                Notifications
    You must be signed in to change notification settings 
- Fork 44
Error Handler
        Thiago da Rosa de Bustamante edited this page Feb 6, 2018 
        ·
        3 revisions
      
    An ErrorHandler is a function that is called to handle all errors reported by the gateway.
The ErrorHandler middleware should be a valid expressjs error handler function.
Each errorHandler middleware must be defined on its own .js file.
Example:
module.exports = (err, req, res, next) => {
    if (err && err.message) {
        if (res.headersSent) { // important to allow default error handler to close connection if headers already sent
            return next(err);
        }
        const mime = req.accepts('json', 'xml', 'html', 'text');
        res.status(err.statusCode || err.status || 500);
        switch (mime) {
            case 'json':
                res.set('Content-Type', 'application/json');
                res.json({ error: err.message });
                break;
            case 'xml':
                res.set('Content-Type', 'application/xml');
                res.send(`<error>${err.message}</error>`);
                break;
            case 'html':
                res.set('Content-Type', 'text/html');
                res.send(`<html><head></head><body>${err.message}</body></html>`);
                break;
            default:
                res.set('Content-Type', 'text/plain');
                res.send(err.message);
        }
    } else {
        next(err);
    }
};If you need to receive some parameters to initialize your error handler, you can write a factory function, like:
module.exports = function(config) {
    validateMustacheConfig(config);
    const template = config.template;
    return (err, req, res, next) => {
        if (err && err.message) {
            if (res.headersSent) { 
                return next(err);
            }
            res.set('Content-Type', config.contentType || 'text/html');
            res.status(err.statusCode || err.status || 500);
            let body;
            try {
                body = mustache.render(template, {
                    error: err,
                    req: req,
                    res: res
                });
            } catch (e) {
                body = { error: err.message };
            }
            res.send(body);
        } else {
            next(err);
        }
    };
};
module.exports.factory = true;You can configure an errorHandler middleware through:
- Admin Rest API: POST /midleware/errorhandler
- SDK: sdk.middleware.addErrorHandler(name, fileName);
- CLI: treeGatewayConfig middleware errorHandler -a <name> ./filename.js
Tree Gateway provide some error handler middlewares for common tasks already included in its distribution. Check the list here.