Extending Error in Javascript with ES6 syntax & Babel

后端 未结 14 1859
你的背包
你的背包 2020-11-28 01:28

I am trying to extend Error with ES6 and Babel. It isn\'t working out.

class MyError extends Error {
  constructor(m) {
    super(m);
  }
}

var error = new          


        
14条回答
  •  感情败类
    2020-11-28 01:52

    I prefer more strong syntax than described above. Additional methods at error type will help you to create pretty console.log or something else.

    export class CustomError extends Error {
        /**
         * @param {string} message
         * @param {number} [code = 0]
         */
        constructor(message, code = 0) {
            super();
    
            /**
             * @type {string}
             * @readonly
             */
            this.message = message;
    
            /**
             * @type {number}
             * @readonly
             */
            this.code = code;
    
            /**
             * @type {string}
             * @readonly
             */
            this.name = this.constructor.name;
    
            /**
             * @type {string}
             * @readonly
             */
            this.stack = CustomError.createStack(this);
        }
    
        /**
         * @return {string}
         */
        toString() {
            return this.getPrettyMessage();
        }
    
        /**
         * @return {string}
         */
        getPrettyMessage() {
            return `${this.message} Code: ${this.code}.`;
        }
    
        /**
         * @param {CustomError} error
         * @return {string}
         * @private
         */
        static createStack(error) {
            return typeof Error.captureStackTrace === 'function'
                ? Error.captureStackTrace(error, error.constructor)
                : (new Error()).stack;
        }
    }
    

    To test this code you can run something similar:

    try {
        throw new CustomError('Custom error was thrown!');
    } catch (e) {
        const message = e.getPrettyMessage();
    
        console.warn(message);
    }
    

    Extending of CustomError type are welcome. It is possible to add some specific functionality to the extended type or override existing. For example.

    export class RequestError extends CustomError {
        /**
         * @param {string} message
         * @param {string} requestUrl
         * @param {number} [code = 0]
         */
        constructor(message, requestUrl, code = 0) {
            super(message, code);
    
            /**
             * @type {string}
             * @readonly
             */
            this.requestUrl = requestUrl;
        }
    
        /**
         * @return {string}
         */
        getPrettyMessage() {
            const base = super.getPrettyMessage();
    
            return `${base} Request URL: ${this.requestUrl}.`;
        }
    }
    

提交回复
热议问题