不再需要 Try/Catch:TypeScript 中处理错误的更好方法
大家好。
在使用 TypeScript 开发应用程序时,您是否觉得 Try/Catch 有点不方便?
我在 YouTube 上发现了一个有趣的视频,它以一种简单的方式描述了如何处理 TypeScript 中的错误。
我分享一下视频中的一些见解,作为回顾。
如果您还有其他好的选择可以尝试/捕捉,我很乐意听到!
定义 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”。我只想在这个 try/catch 块里处理 getUser 中发生的错误。
const wait = (duration: number) => {
...
};
const getUser = async (id: number) => {
...
};
try {
const user = await getUser(1);
console.log(usr); // ← There was an error
// ... (a lot of code)
} 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);
// ... (a lot of code)
} catch (error) {
console.log("There was an error");
}
console.log(usr); // ← ReferenceError: Can't find variable: usr
我从拼写错误中得到了一个实际错误,但是这个代码仍然不理想,因为我可能会意外地重新定义用户对象,如下所示。
const wait = (duration: number) => {
...
};
const getUser = async (id: number) => {
...
};
let user;
try {
user = await getUser(1);
// ... (a lot of code)
} catch (error) {
console.log("There was an error");
}
user = 1 // ← ❌ It might lead to a bug.
解决方案
你不觉得这样更简洁易读吗?
而且,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);
请看一下我们引用的视频。他解释得很仔细。
我从未在实际工作中使用过这种模式。我只是想听听你对它实用性的看法。因为他在 Yotube 的评论里讨论过这个问题,所以我很想知道答案。我会根据评论来探索最佳实践。👍
祝您编码愉快☀️
文章来源:https://dev.to/noah-00/no-more-trycatch-a-better-way-to-handle-errors-in-typescript-5hbd