【问题标题】:customize error message of throw exception javascript自定义抛出异常javascript的错误信息
【发布时间】:2015-01-14 03:41:00
【问题描述】:

我正在尝试为 javascript 中的异常抛出自定义错误消息。

到目前为止,我的尝试都失败了。

我正在尝试这个,但它不起作用

  function abc(sender, args) {
    alert("ex2");
    throw ("error new"); 
    alert("");
  }

【问题讨论】:

    标签: javascript jquery exception


    【解决方案1】:

    您需要throw 和object(具有name 和message 属性)而不是string 来生成自定义exception:

    function abc(sender, args) {
      alert('ex2');
    
      throw {
        name: 'YourErrorName',
        message: 'YourErrorMessage'
      }; 
    
      alert('');
    }
    

    以下是如何引发事件并捕获包含您的姓名和消息值的 exception 的示例:

    function triggerError(){
      throw {
        name: 'YourErrorName',
        message: 'YourErrorMessage'
      }; 
    };
    
    (function cathError(){
      try {
        triggerError();
      }
      catch(e){
        console.log(e.message);
        console.log(e.name);
      }
    }());
    

    查看此codepen 以了解它的工作原理。

    【讨论】:

    • 什么代码?我已经发布了我的代码,仅此而已
    • @fali 我觉得你对 throw 和 exceptions 的用法有误解,再次检查答案。
    【解决方案2】:

    这个简单的代码让我很幸运:

    throw new Error("Something terrible has happened");
    

    当您简单地抛出一个字符串时,您将失去诸如错误堆栈之类的功能。在调用堆栈的某个地方,您可能想要执行以下操作:

    catch(err) {
        console.log(err.stack);
        alert(err.message);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-18
      • 2014-03-15
      • 1970-01-01
      • 2020-02-18
      • 2017-02-28
      • 1970-01-01
      • 2011-10-06
      相关资源
      最近更新 更多