Custom error class in TypeScript

后端 未结 5 519
别跟我提以往
别跟我提以往 2020-12-02 12:06

I\'d like to create my own error class in TypeScript, extending core Error to provide better error handling and customized reporting. For example, I want to cre

5条回答
  •  北海茫月
    2020-12-02 12:50

    There is a neat library for this at https://www.npmjs.com/package/ts-custom-error

    ts-custom-error allow you to create error custom Error very easily:

    import { CustomError } from 'ts-custom-error'
     
    class HttpError extends CustomError {
        public constructor(
            public code: number,
            message?: string,
        ) {
            super(message)
        }
    }
    

    usage:

    new HttpError(404, 'Not found')
    

提交回复
热议问题