DEV Community

Cover image for Wrapper function

Wrapper function

Abayomi Ogunnusi on February 01, 2023

Error handling in Node.js can be done using try-catch blocks, which allow you to handle exceptions thrown by your code. However, this approach ca...
Collapse
 
kareemalkoul profile image
kareem alkoul • Edited

If you want to handle error in express routes, you don't need to wrap the controller with a wrapper function, just use express-async-errors and create error middleware handling for handling errors.
Look to the docs for know how to use it

Collapse
 
drsimplegraffiti profile image
Abayomi Ogunnusi

I have used this package too. Thanks for the contribution

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
drsimplegraffiti profile image
Abayomi Ogunnusi

@abhaysinghr1 Thanks for the comment

Collapse
 
wilmela profile image
Wilmela

Great post. Makes a cleaner code.

Collapse
 
drsimplegraffiti profile image
Abayomi Ogunnusi

Thanks @wilmela. Glad it was helpful

Collapse
 
fredabod profile image
FredAbod

This was very helpful sir...

So with just that one handleCallBack function it can be applied to all the routes?

Collapse
 
drsimplegraffiti profile image
Abayomi Ogunnusi

Yes, you will just follow the same syntax as shown in the getAllTrips controller function

Collapse
 
melroy89 profile image
Melroy van den Berg • Edited

I already use this, thanks very useful! Just thinking.. Can we add some kind of middle-ware code? Like how express-async-error solves it? Since we still need to repeat ourselves now on each API end-point.

Collapse
 
mbugua70 profile image
john mbugua

Have been trying to find resources i can read about this, can you recommend one, I can't any in the express main documentation.

Collapse
 
mbugua70 profile image
john mbugua

But this is really helpful, Thank you