繁体   English   中英

如何在不抛出的情况下抛出错误

[英]How to throw an error without throw

最近我被问到一个问题

有没有办法抛出错误而不使用java中的throw

据我所知,错误只有一种方法可以在JavaScript中抛出错误,并且在JavaScript中使用了throw语句,如下所示:

 var myFunc = () => { // some code here throw 'Some error' // in a conditional // some more code } try { myFunc() }catch(e) { console.log(e) } 

不知道我说的任何其他方式No, there is no other way 但现在我想知道我是不对的?

所以问题是你是否可以在不使用throw情况下在JavaScript中抛出自定义错误


限制:

  • 请不要使用evalFunction
  • 不要在代码中使用throw

附加:

如果您可以在不使用单词Error情况下抛出Error

生成器确实有一个throw方法,通常用于将异常抛出到生成器函数代码中(在yield表达式的位置,类似于next ),但是如果没有捕获它,它会从调用中冒出来:

(function*(){})().throw(new Error("example"))

当然,这是一个黑客而不是好的风格,我不知道他们所期望的答案。 特别是“不分零”的要求是粗略的,因为除以零不会在JS中抛出异常。

如果您只想抛出错误,那么只需执行无效操作。 我在下面列出了几个。 在浏览器控制台上运行它们以查看错误(在chrome和firefox上测试)。

 var myFunc = () => { encodeURI('\?'); // URIError a = l; // ReferenceError null.f() // TypeError } try { myFunc() }catch(e) { console.log(e); } 

 function throwErrorWithoutThrow(msg) { // get sample error try { NaN(); } catch (typeError) { // aquire reference to Error let E = typeError.__proto__.__proto__.constructor; // prepare custom Error let error = E(msg); // throw custom Error return Promise.reject(error); } } throwErrorWithoutThrow("hi") /* catch the error, you have to use .catch as this is a promise that's the only drawback, you can't use try-catch to catch these errors */ .catch((e) => { console.log("Caught You!"); console.error(e); }); 

我想,如果你想使用try...catch块,你需要抛出一些东西才能找到catch部分。 您可以使用几乎所有失败并出现错误的内容(如其他帖子中所述)。

如果在某些时候,你想在不必自己编写throw语句的情况下运行或死掉 ,你总是可以做一个断言:

const myFunction = () => {
  try {
    assert.fail();
    console.log(`Did not work :)`);
  } catch (e) {
    console.log(`OK`);
  }
};

当然,我宁愿尝试断言积极的东西(更多的禅宗),我需要继续。

const myTypeErr = () => `This is a Custom Err Message... \nand it`()

try {
  myTypeErr()
} catch(e) {} // catched

myTypeErr() // Uncaught TypeError: "This is a Custom Err Message... 
              // and it" is not a function

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM