[JS] Error Handling
keywords: exception handling
, javascript
, 錯誤處理
, 例外處理
Error Handling 的重要概念
參考資料
- 說明可能 catch 不到 error 的情況:try...catch @ javascript.info
Uncaught Error
當錯誤都沒有被處理時,最終會拋到最外層,這時候:
- Node.js:
process.on('uncaughtException')
會被觸發 - 瀏覽器:
window.onerror = function(message, url, line, col, error){}
會被觸發
Custom Error
參考資料
- Better error handling with unknown type in TypeScript @ Youtube
- Custom Error Class @ Udemy
- Handling errors like a pro in TypeScript @ Medium
- Custom Error Types @ MDN
create custom error class
// error.ts
export class ApiError extends Error {
status: number;
constructor(url: string, status: number) {
super(`Request fail with ${status} on ${url}`);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ApiError);
}
this.name = 'ApiError';
this.status = status;
}
}
throw custom error
// fetch.ts
export async function fetchJson<T>(url: string): Promise<T> {
const resp = await fetch(url);
if (!resp.ok) {
throw new ApiError(url, resp.status);
}
const data = await resp.json();
return data;
}
use custom error
const fetchProducts = async () => {
try {
const products = await fetchJson('http://example.com');
// ...
} catch (error) {
if (error instanceof ApiError) {
// handle Api Error
// we can use `error.name` and `error.status` in the Custom Error now
}
throw error;
}
};
JavaScript Error Handling Pattern
Either Pattern
參考資料
Async Await try-catch hell @ Youtube Shorts
// return the function with tuple [Data?, Error?]
async function foo() {
try {
const data = await promise;
return [data, null];
} catch (error) {
return [null, error];
}
}
async function main() {
const [data, error] = await foo();
if (error) {
/* ... */
}
const [data, error] = await bar();
}