前言
大家好,我是倔強青銅三。是一名熱情的軟件工程師,我熱衷于分享和傳播IT技術,致力于通過我的知識和技能推動技術交流與創新,歡迎關注我,微信公眾號:倔強青銅三。歡迎點贊、收藏、關注,一鍵三連!!!
用“錯誤捕獲”替代 Try/Catch:TypeScript 錯誤處理新思路
在開發 TypeScript 應用程序時,你是否覺得傳統的 Try/Catch 錯誤處理方式有些繁瑣?最近,我在 YouTube 上看到一個有趣的視頻,介紹了一種更簡潔的錯誤處理方法。今天,我將分享視頻中的核心內容,并結合自己的理解進行總結。
定義 getUser 函數用于錯誤處理
首先,我們定義一個簡單的 getUser
函數來演示錯誤處理。該函數根據給定的 id
返回一個用戶對象。
const wait = (duration: number) => {
return new Promise((resolve) => {
setTimeout(resolve, duration);
});
};
const getUser = async (id: number) => {
await wait(1000);
if (id === 2) {
throw new Error("404 - User does not exist");
}
return { id, name: "Noah" };
};
const user = await getUser(1);
console.log(user); // { id: 1, name: "Noah" }
使用 try/catch 進行錯誤處理
將上述代碼改寫為使用 try/catch 的形式,代碼如下:
const wait = (duration: number) => {
...
};
const getUser = async (id: number) => {
...
};
try {
const user = await getUser(1);
console.log(user); // { id: 1, name: "Noah" }
} catch (error) {
console.log("There was an error");
}
try/catch 的問題 ①:捕獲了 try 塊內的所有錯誤
以下代碼存在問題。即使只是一個拼寫錯誤,控制臺也會顯示“There was an error
”,而我只想捕獲 getUser
中發生的錯誤。
const wait = (duration: number) => {
...
};
const getUser = async (id: number) => {
...
};
try {
const user = await getUser(1);
console.log(usr); // ← 拼寫錯誤
// ... (大量代碼)
} catch (error) {
console.log("There was an error");
}
try/catch 的問題 ②:使用 let 的陷阱
嘗試使用 let
解決問題,代碼如下:
const wait = (duration: number) => {
...
};
const getUser = async (id: number) => {
...
};
let user;
try {
user = await getUser(1);
// ... (大量代碼)
} catch (error) {
console.log("There was an error");
}
console.log(usr); // ← ReferenceError: Can't find variable: usr
雖然拼寫錯誤引發了實際錯誤,但這段代碼仍不理想,因為可能會意外重新定義 user
對象,例如:
const wait = (duration: number) => {
...
};
const getUser = async (id: number) => {
...
};
let user;
try {
user = await getUser(1);
// ... (大量代碼)
} catch (error) {
console.log("There was an error");
}
user = 1; // ← ? 可能引發錯誤
解決方案
使用 catchError
函數可以更簡潔、更易讀地處理錯誤。此外,user
變量是不可變的,不會引發意外錯誤。
const wait = (duration: number) => {
...
};
const getUser = async (id: number) => {
...
};
const catchError = async <T>(promise: Promise<T>): Promise<[undefined, T] | [Error]> => {
return promise
.then((data) => {
return [undefined, data] as [undefined, T];
})
.catch((error) => {
return [error];
});
};
const [error, user] = await catchError(getUser(1));
if (error) {
console.log(error);
}
console.log(user);
如果你對這種模式是否實用有疑問,可以參考視頻中的詳細解釋。