Extending Error in Javascript with ES6 syntax & Babel

后端 未结 14 1758
你的背包
你的背包 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 02:04

    I improved a little the solution of @Lee Benson this way:

    extendableError.js

    class ExtendableError extends Error {
        constructor(message, errorCode) {
            super(message);
            this.name = this.constructor.name;
            this.errorCode = errorCode
            if (typeof Error.captureStackTrace === 'function') {
                Error.captureStackTrace(this, this.constructor);
            } else {
                this.stack = (new Error(message)).stack;
            }
        }
    
    
    }
    
    export default ExtendableError
    

    an example of an error

    import ExtendableError from './ExtendableError'
    
    const AuthorizationErrors = {
        NOT_AUTHORIZED: 401,
        BAD_PROFILE_TYPE: 402,
        ROLE_NOT_ATTRIBUTED: 403
    }
    
    class AuthorizationError extends ExtendableError {
        static errors = AuthorizationErrors 
    }
    
    export default AuthorizationError 
    

    Then you are able to group errors while having option specifiers to decide what to do differently in some of your application specific situations

    new AuthorizationError ("The user must be a seller to be able to do a discount", AuthorizationError.errors.BAD_PROFILE_TYPE )
    
    0 讨论(0)
  • 2020-11-28 02:11

    As @sukima mentions, you cannot extend native JS. The OP's question cannot be answered.

    Similar to Melbourne2991's answer, I did used a factory rather, but followed MDN's recommendation for customer error types.

    function extendError(className){
      function CustomError(message){
        this.name = className;
        this.message = message;
        this.stack = new Error().stack; // Optional
      }
      CustomError.prototype = Object.create(Error.prototype);
      CustomError.prototype.constructor = CustomError;
      return CustomError;
    }
    
    0 讨论(0)
提交回复
热议问题