TL Errors
An ExpressJS middleware to handle custom errors.
Requirements:
Installation
npm install --save tl-errors
Configuration
The first step is to create your configuration file. Here you can define your custom errors, redirection urls and excluded requests.
This package comes with a default configuration that you can extend or overwrite.
Sample configuration file
const config = {
errors: [
{
name: 'EnhanceYourCalmError',
message: 'Breath in... Breath out...'
code: 420
},
{
name: 'BadRequestError',
message: 'The request could not be understood by the server due to malformed syntax.'
code: 400
}, {
name: 'ConflictError',
message: 'This document is already registered.',
code: 409
}
],
handlers: {
'ValidationError': 'BadRequestError',
'11000': 'DuplicatedEntityError'
},
exclude: /^\/(assets|api)\//i,
redirect: {
error: '/error?err=',
lost: '/lost?url='
},
debug: err => {
console.log('START ERROR LOG:', new Date());
console.log(err);
console.log('END ERROR LOG:', new Date());
},
shouldDebug: err => err.code > 399
};
Usage
To use the package you must configure it and then bind it to the express application.
Binding the component
const errors = require('tl-errors');
const express = require('express');
const app = express();
errors.config(config);
app.use(errors.notFoundMiddleware);
app.use(errors.handler);
Using the component
const errors = require('tl-errors');
const { BadRequestError } = errors;
module.exports = (router, db) => {
const User = db.model('user');
router.post('/', async (req, res, next) => {
try {
const user = await User.create(req.body);
if (!user) {
throw new BadRequestError('The user could not be created');
}
res.status(HTTP_CODE_CREATED).json(user._id);
} catch (err) {
next(err);
}
});
}
Every error triggered in a middleware will be caught inside the component.
Documentation
Read the library docs for the methods specification.