Error handling

Error handling is the process of an application catching errors and processing them. These errors usually occur during runtime of an application. It does not matter if an error is synchronous or asynchronous. A default error handler is embedded by default in Express.js hence, it's not required for you to write a specific error handler to get started on a new application as we did.

It is necessary for Express.js to catch any errors that occur while running route handlers and middleware, otherwise errors will be lost. As mentioned, there are some default error handlers for errors that occur in synchronous code inside route handlers and middleware. In the case of default error handlers, no extra work is needed. In other words, if asynchronous code throws an error, then Express.js will catch it and process it by default, as in the following example:

export let getSomething = (req: Request, res: Response, next: NextFunction) => {
throw new Error("doh! Something went wrong :( ")
})

So, if you have asynchronous functions that are invoked by route handlers and middleware, they must be passed to the next() function. That way, Express.js will catch and process them automatically, as in the following example:

...
import * as fs from 'fs'
...

export let getSomething = (req: Request, res: Response, next: NextFunction) => {
fs.readFile("/PATH_TO_A_FILE_THAT_NOT_EXISTS", (error, data) => {
if (error) {
// no worries, just pass the errors to Express through next function
next(err);
}
else {
res.status(200).send(data)
}
})
})

There is also another possibility available, which is evolving the code in a try...catch block in order to catch errors in asynchronous code and pass them back to Express.js:     

If a try...catch block is ignored, Express.js will not be able to catch any errors because it is no longer part of the asynchronous handler scope.
export let getApi = (req: Request, res: Response, next: NextFunction) => {
Promise.resolve()
.then(() => {
throw new Error('doh! Something went wrong :( ')
})
.catch(next)
}

For instance, in the preceding code, the error will be passed to Express.js on the catch scope.

..................Content has been hidden....................

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