Skip to main content

Custom Handler

Unified Errors Handler provide an easy way to implement your custom handler using exceptionMapper function and with this function you can use Unified Errors Handler with any NodeJS app.

const express = require('express');
const { exceptionMapper } = require('unified-errors-handler');

const app = express();
/**
response in case of error will be
{
errors: [
{
code: 'USER_NOT_FOUND',
message: 'user not found',
},
],
}
with status code 404
*/
app.post('/test', function (req, res) {
const isFound = // ...
if (isFound) {
// return response
} else {
throw new NotFoundException([
{
code: 'USER_NOT_FOUND',
message: 'user not found',
},
]);
}
});

app.use((err: Error, req: any, res: any, next: any) => {
const mappedError = exceptionMapper(err);

res.status(mappedError.statusCode).send({
errors: mappedError.serializeErrors(),
});
});