# Promise Error Handling ###### tags: `slide` #### Backend Camp | Zen --- ## 什麼是Error Handling? Error Handling就是把錯誤完整地拋給使用者知道 --- ## Promise 如何抓到Error --- ## 範例1 ```javascript new Promise((resolve, reject) => { console.log('Initial'); reject('errorerrorerror'); }) .then(() => { console.log('Do this'); }) .catch((err) => { console.log('Do not do that '+ err); }) ``` --- ### promise().catch(onRejected); ###### 若 onRejected 拋出一個錯誤或回傳一個被拒絕的 Promise,則 catch() 回傳的 Promise 被拒絕;其他情形都是被實現。 --- ## 範例2 ###### 因為JS語言會把err(錯誤) 給throw出來,所以.catch()可以接到。 ```javascript new Promise((resolve, reject) => { console.log('Initial'); fsfsdfsdfdsffdsfddfdfsdfsdfdsfsdf //我是錯誤 }) .then(() => { console.log('Do this'); }) .catch((err) => { console.log('Do not do that'+ err); }) ``` --- ### 隱式 try…catch ###### Promise 的執行者(executor)和 promise 的處理程序(handler)周圍有一個「隱式的 try..catch」。如果發生異常,它就會被捕獲,並被視為 rejection 進行處理。 --- ### 最後一種, ### Handle 方式是寫在內層 function 裡面 --- <div style="text-align: left;"><font size = "6"> ```javascript function errorExample() { result = new Promise((res, rej) => { fsfsdfsdfdsffdsfddfdfsdfsdfdsfsdf //我是錯誤 }).catch((error) => { return "errorerrorerror" }) return result; } errorExample() .then((success) => { console.log('Do this ' + success); }) //Do this handle by inner function .catch((err) => { console.log('Do not do that' + err); }) ``` </font></div> ---
{"metaMigratedAt":"2023-06-15T09:40:29.632Z","metaMigratedFrom":"Content","title":"Promise Error Handling","breaks":true,"contributors":"[{\"id\":\"30e59c9a-3d1d-4bc1-8daa-c97ff56595a3\",\"add\":2989,\"del\":1488}]"}
    311 views