What are the types of the four parameters for the error handling function when coding in Typescript?
app.use((err: ??, req: ??, res: ??, next: ??) => { }
Using any completely gives up the type checking advantage of the Typescript. For err parameter, it's recommended to create your own type or class like following:
// HttpException.ts in exceptions directory of your project.
export class HttpException extends Error {
public status: number
public message: string
constructor(status: number, message: string) {
super(message)
this.status = status
this.message = message
}
}
And then import it for your error-handling middleware:
import { HttpException } from './exceptions/HttpException'
app.use((err: HttpException, req: Request, res: Response, next: NextFunction) => {
err.status = 404
err.message = 'Not Found'
next(err)
})
We can add any properties and methods to the HttpException class as and when required, like we have added status and message.
In case you haven't done already, you need to install type definitions for Node.js and Express.js for your Typescript project. This will make sure the types Request, Response and NextFunction will be recognised and auto-imported.
To install type definitions for Node.js:
npm install --save-dev @types/node
To install type definitions for Express.js:
npm install --save-dev @types/express
That's it! Hope that helps.