I build custom error class with typescript :
class AppError extends Error{
constructor(message: string, statusCode: Number){
super(<string>message);
this["statusCode"] = statusCode,
this["status"] = `${statusCode}`.startsWith('4') ? 'fail' :'error'
this["isOperational"] = true;
Error.captureStackTrace(this, this.constructor)
}
}
I use this error handling:
app.all('*', (req: Request, res:Response, next: NextFunction)=>{
next(new AppError(`Can\'t find ${req.originalUrl} on this server`, 404))
})
Here problem. How to get type AppError class. I build error handler middleware:
const errorHandler = (err: Error, req:Request, res:Response, next:NextFunction)=>{
console.log(err)
res.status(res.statusCode).json(err.message)
}
How to add AppError type err type?
>Solution :
The err parameter must remain as Error because this handler can be used with any type of error, not just AppError.
What you can do is check if the given err is an instance of AppError as such:
const errorHandler = (err: Error, req:Request, res:Response, next:NextFunction) => {
if (err instanceof AppError) {
// err is an AppError
console.log(err)
res.status(res.statusCode).json(err.message)
} else {
// do some other thing here, err is not an AppError
}
}