path: lib/middleware
- Sends error messages in JSON format from the server to a client
- Must be configured before use
- Uses custom templates with placeholders
const { httpErrorHanlder } = require('error-management');
...
app.use(httpErrorHandler({
template: {
error: true,
message: '%message%'
}
}));
Option | Description |
---|---|
template | Contains Single template (Object) or Multiple templates (Array of objects). |
examlpe (Single template):
{
...
template: {
error: true,
message: '%message%'
},
...
}
When using Multiple templates each one should have required options:
Option | Description |
---|---|
template | Template in the format similar to Single template |
default | Default template flag, should be set to 'true' |
condition | Object with conditions when to select exactly this template |
Defines selection rules for choosing a template
Option | Description | Example |
---|---|---|
httpStatusCode | matches against error http status code returned by library helper getHTTPStatusCode | httpStatusCode: 500 |
Placeholders are used to define the place for a value taken from the corresponding Error property. For instance, an error like this:
error = new Error('Some error');
error.name = 'ValidationError';
with the template:
{
template: {
error: true,
message: '%message%',
data: {
name: '%name%'
}
}
}
results in JSON format error message sent to a client:
{
error: true,
message: 'Some error',
data: {
name: 'ValidationError'
}
}
Currently supported placeholders:
- %code%
- %extra%
- %message%
- %name%
example 1: Single template
httpErrorHandler({
template: {
error: true,
message: '%message%'
}
})
example 2: Multiple templates
httpErrorHandler({
template: [
{
default: true,
template: {
status: 'fail',
data: '%extra%'
}
},
{
condition: {
httpStatusCode: 500
},
template: {
status: 'error',
message: '%message%'
}
}
]
})
- Checks if passed a mongoose error
- Extracts mongoose specific data and updates error object properties with it
- Passes modified error to the next express middleware
const { mongooseErrorConverter } = require('./errorManagement');
...
app.use(mongooseErrorConverter());
usage with httpErrorHandler:
const { httpErrorHanlder, mongooseErrorConverter } = require('./errorManagement');
...
app.use(mongooseErrorConverter());
app.use(httpErrorHandler({
template: {
error: true,
message: '%message%'
}
}));
Currently supported:
- ValidationError
path: lib/helpers
Returns http status code corresponding to the given error name.
...
const httpStatusCode = getHTTPStatusCode('ValidationError');
console.log(httpStatusCode); // -> 400
- add parseMongoose option instead of using mongooseErrorConverter middleware