Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get type custom error class typescript?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading