[WP] 09.03.2023 | error handling

fig 1.1 error handling in express

 I would like to dedicate this post to error handling in express js and node js based application. Errors without handlers stop the servers runtime and crash the application. It blocks the runtime of the API. Error handlers role is to prevent server from crashing and return explicit error message and status code.

The first solution is to pass error handler as a middleware. It will catch all synchronous errors thrown inside apps middlewares and handlers.



app.get("/", () => { throw new Error("message") // error thrown within "/" route handler. });


Thus a handler is added to the bottom of the router stack and collects all the errors which have been thrown before. Each time the error is thrown – error handler middleware is triggered. The structure of error handler is same as of a middleware except for err and next parameters are added.



app.use((err, req, res, next) => { // block of code to handle an error });



The second solution solves problem with asynchronous errors. To handle an error within asynchronous function we need to put try…catch statement and pass error into next method. Anything passed into next method will be considered an error.



const handler = async (req, res, next) = { // .... try { // handler block of code goes here... } catch(e) { next(e) } }


When looking for solution for error problem we can also create something called custom error handler. It makes possible to pass errors to any reporting service(eg. sentry). There can be more than one handler established to log the error, report it and respond to the request. Error properties may be augmented here before passing it into the next(e) method.



catch (e) { e.type = 'input' next(e) } app.use((err, req, res, next) => { if (err.type === 'input') { res.status(400) return res.send('invalid input') } })


During the error handling process it is crucial to cover all possible cases when error may occur to provide stability of the server app and best quality experience to the user.


Thanks for reading

g-marcin

Komentarze

Popularne posty z tego bloga

[WP] 23.06.2023 | subjects

15.07.2024 | simplicity

[WP] 05.06.2023 | angular-intro