Closed sashankshukla closed 1 year ago
we already specify app.use(errorHandler)
in app.js so we just need all routes to use this next() and then the thunks should be able to handle errors and server wont crash
Check out errorMiddleware for more details about what its doing
Traversy makes use of express async handler , https://github.com/bradtraversy/mern-tutorial/tree/main/backend/controllers. Feel free to try this way instead too.
Currently, when there is some sort of error (server or validation) we use
throw new Error
with a status code. This is kind of problematic since it breaks the server every time. We need a try-catch in each of our API controllers to use our errorMiddleware which deals with any errors we throw as well as server or mongoose errors. This will prevent the server from breaking.An example refactor would look like this: Before
After