不再需要 Try/Catch:TypeScript 中处理错误的更好方法

2025-05-25

不再需要 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" }
Enter fullscreen mode Exit fullscreen mode

使用 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");
}
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

我从拼写错误中得到了一个实际错误,但是这个代码仍然不理想,因为我可能会意外地重新定义用户对象,如下所示。

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.
Enter fullscreen mode Exit fullscreen mode

解决方案

你不觉得这样更简洁易读吗?
而且,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);
Enter fullscreen mode Exit fullscreen mode

请看一下我们引用的视频。他解释得很仔细。

我从未在实际工作中使用过这种模式。我只是想听听你对它实用性的看法。因为他在 Yotube 的评论里讨论过这个问题,所以我很想知道答案。我会根据评论来探索最佳实践。👍

祝您编码愉快☀️

文章来源:https://dev.to/noah-00/no-more-trycatch-a-better-way-to-handle-errors-in-typescript-5hbd
PREV
对跨性别者友善的 9 种方法 1. 不要转发我的仇恨邮件 2. 一定要学习“顺性别”这个词 3. 不要认为跨性别恐惧症是孤立的或罕见的 4. 不要在背后说我坏话 5. 不要跟我谈论 Drag Race 6. 一定要在你的个人简介中写上你的代词 7. 不要要求我在我的个人简介中写上我的代词 8. 如果你犯了错误:道歉并继续前进 9. 一定要跟我谈谈你对性别的感受
NEXT
UI 开发人员的 10 个 CSS 技巧