'Node js express error hanlding middleware dont recognize 4 elements

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

3 parameters identified

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.



Solution 1:[1]

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. ')
    }
})

Solution 2:[2]

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.

abdurrahim answer really helped in figuring it out, after I added the code he attached I saw it was catching the errors, and the "500 server error" is, technically, an error-handling middleware.

So I added the following code after all the routes in the routes file, and managed to handle the different errors I was throwing.

Thanks a bunch!

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 roy