【问题标题】:How to override the built-in exception?如何覆盖内置异常?
【发布时间】:2019-08-26 23:41:09
【问题描述】:

我在一个整数变量上使用 array.pop() 函数并期待一个错误。 目前,我收到“TypeError:x.pop 不是函数”消息。 我想使用“throw”用我自己的消息覆盖它

我尝试在第一个 catch 块中使用另一个 try-catch,这样就完成了工作。但我想在第一个 try 块本身中覆盖第一个 TypeError 异常。

let x = 3
try {
    x.pop();
// I want to override the exception generated due to this line 
// with my own error message using throw
}
catch (e) {
    try {
        throw thisErr("this is my custom error message..")
    }
    catch (er) {
        console.log(er);
    }
}

function thisErr(message) {
    let moreInfo = message
    let name = "My Exception"
    return `${name}: "${moreInfo}"`
}

我期待My Exception: "this is my custom error message.."

【问题讨论】:

    标签: javascript error-handling try-catch throw


    【解决方案1】:

    快速方法: 您可以使用 Error 构造函数创建一个 Error 对象并将其用作定义自定义异常的基础。当没有多个需要抛出自定义异常的实例时,通常可以使用此方法。

    let x = 3;
    try {
        x.pop();
    } catch (e) {
        throw new Error({ 
            name: "My Exception",
            message: "this is my custom error message..", 
            toString: function() { return `${this.name} : ${this.message}` } 
        });
    }
    

    更好的方法: 创建一个类 CustomError 并为这个自定义类定义你自己的构造函数。这种方法更好,更健壮,可以在您的应用程序在很多地方需要自定义异常时使用。

    class CustomError extends Error {
        constructor(name, message, ...params) {
        // Pass remaining arguments (including vendor specific ones) to parent 
        constructor
            super(...params);
    
            this.name = name;
            this.message = message;
    
            // Maintains proper stack trace for where our error was thrown (only available on V8)
            if (Error.captureStackTrace) {
                Error.captureStackTrace(this, CustomError);
            }
        }
    }
    
    let x = 3;
    try {
        x.pop();
    } catch(e){
        throw new CustomError('My Exception', 'this is my custom error message..', e);
    }
    

    【讨论】:

      【解决方案2】:

      使用console.error(er)

      let x = 3
      try {
          x.pop();
      }
      catch (e) {
      
              var er = thisErr("this is my custom error message..");
              // log(black)  My Exception: "this is my custom error message.."
              console.log(er);
              // error(red)  My Exception: "this is my custom error message.."
              console.error(er);
              // error(red) Uncaught My Exception: "this is my custom error message.."
              throw er;
      
      }
      function thisErr(message) {
          let moreInfo = message
          let name = "My Exception"
          return `${name}: "${moreInfo}"`
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-18
        • 2012-08-07
        • 2016-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-27
        相关资源
        最近更新 更多