I'm trying to create an error-handling middleware, and as you can see in the image attached when I'm making the
app.use((err,req,res,next) => {...})
block my IDE is automatically recognized as 3 parameter middleware. and I can't get it to work as err-req-res-next middleware. I thought - maybe the IDE miss-indexed that block - and tried to run it, and while running the express doesn't recognize an error-handling middleware
I add the "app.use" in my server.js (which is the same as app.js), and as the last-placed app.use, right before the listen.
I'm using latest express to date: 4.18.1
Any help in finding a solution will be great!
Many thanks.
CodePudding user response:
Add these two after all routing methods:
// 404 not found error
app.get('*', (req, res) => {
res.status(404).send('<h1>error 404 not found</h1>');
})
// 500 server error
app.use((error, req, res, next)=>{
if(error){
res.send('500 OOPS :( Something went wrong... Please try again. ')
}
})
CodePudding user response:
Figured it out!
The issue was that I added the "error handling middleware" at the "server.js", it should have been in the placeholder.routes.js of the relevant controller.