'NodeJs/ Typescript errorhandler typing

I am using NodeJs/express and Typescript.

at the moment when I do a request, the compiler find understand the type of (req, res), and I do not need to do anything.

UserRouter.post('/user/me/avatar', avatar, async (req, res) => {
    res.status(200).send();
})

I am trying to add an errorHandler to my route. when the middlewear throw an error, I would like to execute a function.

I saw that you can do the following

UserRouter.post('/user/me/avatar', avatar, async (req, res) => {
    console.log(res)
    res.status(200).send();
}, (error, req, res, next) => {
    res.status(400).send({error : error.message});
})

this works, but typescript compiler do not understand the type and throw an error

Parameter 'error' implicitly has an 'any' type.ts(7006)

I have to write everything with any or I always get a compiler error even if I try to do

UserRouter.post('/user/me/avatar', avatar, async (req: Request, res: Response) => {
    console.log(res)
    res.status(200).send();
}, (error: Error, req :Request, res :Response, next: NextFunction) => {
    res.status(400).send({error : error.message});
})

Is there another way to call this error catch ?



Solution 1:[1]

You can set the accordant option in your tsconfig.json to prevent/suppress these errors:

"compilerOptions": {
  ...
  "noImplicitAny": false,
  ...
}

--noImplicitAny Raise error on expressions and declarations with an implied any type.

Edit

UserRouter.post('/user/me/avatar', avatar, async (req: Request, res: Response) => {
    console.log(res)
    res.status(200).send();
}, (error: Error, req :Request, res :Response, next: NextFunction) => {
    res.status(400).send({error : error.message});
})

Works fine for me.

Solution 2:[2]

try { this.response.send({ code:200, data: response }) } catch(error) {

    this.response.status(error.Code || 400). send ({
        code:error.code,
        message:error.message
    })

}

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 Raghavendra Hn