1.0.5 • Published 7 years ago
express-json-errors v1.0.5
express-json-errors
An error handler for JSON APIs. They follow the general 'spec' outlined here
Example
var express = require('express'),
errorHandler = require('express-json-errors');
var app = new Express();
app.use(errorHandler());
// An simple example "route" or middleware
app.use((req, res) => {
res.error('This is a JSON error!');
/**
* This will output as JSON to the response
* {
* code: 400,
* errors: [
* {
* code: 400,
* title: 'This is a JSON error!',
* description: 'n/a'
* }
* ]
* }
*/
});
API
By default you have res.error
to use. You can send it Strings, plain Objects, Errors, Arrays (containing any combination of Strings, Objects, or Errors).
// Using strings
app.use((req, res) => {
res.error('This is a JSON error!');
});
// Using Objects
app.use((req, res) => {
res.error({
code: 404,
title: 'That resource was not found',
description: 'I could not find the resource `my_resource`.'
});
});
// Using Errors
app.use((req, res) => {
res.error(new Error('This is an error!'));
});
// Using Arrays
app.use((req, res) => {
res.error([
'You did something wrong',
new Error('This is an error!'),
{
title: 'This is really not good!'
}
]);
});
There is also support for express-validator. You can use it like:
app.use((req, res) => {
req.checkBody('my_input', 'Missing my_input parameter').notEmpty();
req.getValidationResult()
.then(result => {
if(!result.isEmpty()) return res.validationError(result.array());
})
.catch(res.error);
});
Status Codes
The API has a somewhat semantic way of handling errors. If you only have on error, the default error code is 400 unless otherwise specified. So for example:
// A single error
app.use((req, res) => {
res.error('This is a JSON error!'); // Will result in a response code of 400
});
// A single error
app.use((req, res) => {
res.error({
code: 404,
title: 'This is a JSON error!'
}); // Will result in a response code of 404
});
If you have multiple errors (aka an array of errors) the system will default to 400. Then each error object in the response will have it's own status code.
If you use a JS error, the status code will be 500. For example:
// A single error
app.use((req, res) => {
res.error(new Error('This is an error!')); // Will result in a response code of 500
});