[英]How to throw an error without throw
最近我被問到一個問題 :
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中拋出自定義錯誤
eval
, Function
。 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.