Writing custom error handlers

To write error handlers using Express.js, you can follow almost the same template as a middleware function, for example:

this.app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('My custom error handler with 500 error...')
})
The error handler must be the last app definition after routes and other calls.

Also, you can define as many error handlers as you want, for instance, one for logging, another one for client errors, and another one for a catch-all error, as follows:

this.app.use(errorHandler.logging)
this.app.use(errorHandler.clientErrorHandler)
this.app.use(errorHandler.errorHandler)

For logging purposes, we want to catch the log and pass the error on the next() function, as follows:

export let logging = (err: Error, req: Request, res: Response, next: NextFunction) => {
logger.error(err)
next(err)
}

On client error, if the error is of the xhr type, we will send a 500 error to the requester, and if it is not, we will again pass the error on the next() function, as follows:

export let clientError = (err: Error, req: Request, res: Response, next: NextFunction) => {
if (req.xhr) {
res.status(500).send({ error: err.message })
} else {
next(err)
}
}

Finally, if none of the previous steps catch the error, the default error handler will catch everything and send a 500 error, as follows:

export let errorHandler = (err: Error, req: Request, res: Response, next: NextFunction) => {
res.status(500).send({ error: err.message })
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.53.202