簡體   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