Custom Error Handling
When using any
, the type checking advantage of Typescript is lost. To maintain type safety, consider using the type unknown
for the err
parameter:
app.use((err: unknown, req: Request, res: Response, next: NextFunction) => { })
Implementation Example
If needed, create a custom error type as shown below:
// 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
}
}
Then import the custom error where required:
import { HttpException } from './exceptions/HttpException'
app.use((req: Request, res: Response, next: NextFunction) => {
const err = new HttpException(404, 'Not Found')
// Handle error here...
next(err)
})
app.use((err: unknown, req: Request, res: Response, next: NextFunction) => {
if (err instanceof HttpException) {
// Perform additional actions for this specific error...
}
next(err)
})
Since the type of err
is unknown
, type checking is required before accessing or modifying it using instanceof
to cast it to the correct type (HttpException
in this case).
Additional properties and methods can be added to the HttpException
class as needed, such as status
and message
.
Setting up Type Definitions
If not done already, install type definitions for Node.js and Express.js in your Typescript project to ensure proper recognition and auto-importing of types like Request
, Response
, and NextFunction
.
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 concludes the setup. Hope this information is useful.