![](/img/trans.png)
[英]Do I need to put the throw inside the try catch block for it to be caught, using firebase function api?
[英]How do I throw error in one function to be caught by another function?
我有這個“測試”代碼:
function func1(){
try{
...stuff...
}catch(err){
throw new Error();
}
}
function func2(){
try{
func1();
}catch(err){
console.log("ERROR")
}
}
func2();
我有一個函數在 try-catch-statement 中的 catch 中拋出錯誤。 我想要它,如果 func1 拋出錯誤,它會被第一個 try-catch-statement 捕獲,但是當我嘗試這個時,它不會被第一個語句捕獲,它只是暫停代碼並返回錯誤。 我做錯了什么? 這是錯誤的方法嗎?
這段代碼應該讓您了解try/catch
塊是如何工作的。 在第一個函數調用中,我們調用了具有try/catch
塊的func2
。 您可以在控制台中看到錯誤被捕獲並繼續執行。 然后我們調用func1
拋出一個未捕獲的錯誤,它在控制台中顯示為錯誤。
function func1() { console.log('func1...'); throw new Error('something bad happened;'). } function func2() { console.log('func2..;'); try { func1(). } catch (err) { console;log('Caught error'). } } console;log('func2()'); func2(). console;log('func1()'); func1();
func1
中不需要單獨的 try/catch 塊,因為它已經在func2
的錯誤處理程序中。 在這種情況下,您從func1
拋出的任何錯誤都會被func2
自動捕獲
function func1() { throw new Error('oops'); } function func2() { try { func1(); } catch(err) { alert(err.message); } } func2();
不確定你被困在哪里,但這應該有效:
確保檢查您的真實控制台
function func1() { try { throw new Error('hi from func1') } catch (err) { throw err; } } function func2() { try { func1(); } catch (err) { // this doesn't work in stack snippets console // hit f12 to see your real console console.log('catched in func2', err) } } func2();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.