简体   繁体   English

如果在我的 catch 块中引发错误的代码被 if 语句包围,为什么 Typescript 会引发错误?

[英]Why does Typescript throw an error if the code that throws an error in my catch block is surrounded by an if statement?

I'm trying to throw an error if the error status code is anything but 401, however, as soon as I enclosed the line of code that throws the error, my typescript started giving me the following error:如果错误状态代码不是 401,我试图抛出一个错误,但是,一旦我包含了抛出错误的代码行,我的打字稿就开始给我以下错误:

To annotate your function a bit:稍微注释一下您的函数:

export const addAccountGoal = async (title: string, color: string): Promise<number> => {
    try {
        const { body: goalId } = await request.post('/goals/account/addGoal').send({ title, color });
        await setActiveGoal(goalId);
        return goalId;
    } catch (e) {
        if (e.status !== 401) {
            throw new Error('GENERIC_ERROR');
        } else {
            // WHAT SHOULD I DO HERE
        }
    }
};

Your problem is that you haven't told TypeScript anything for "what should I do here", so execution continues to the end of the function, where you don't return anything.你的问题是你没有告诉 TypeScript 任何关于“我应该在这里做什么”的事情,所以执行会继续到函数的末尾,你不会返回任何东西。 Hence the error message, "Function lacks ending return statement and return type does not include 'undefined'."因此出现错误消息,“函数缺少结束返回语句并且返回类型不包括‘undefined’。”

Depending on the specific logic you want:根据您想要的特定逻辑:

  • You could explicitly return undefined;您可以显式return undefined; and change the function's return type to Promise<number | undefined>并将函数的返回类型更改为Promise<number | undefined> Promise<number | undefined> . Promise<number | undefined>
  • You could re-throw the error ( throw e; ).您可以重新抛出错误( throw e; )。
  • You could return a default value ( return 0; ).您可以返回默认值( return 0; )。
  • Something completely different完全不同的东西

(The else { that I added is just for explanatory purposes; you don't have to write your code that way unless you want to.) (我添加的else {只是为了解释目的;除非你愿意,否则你不必那样写代码。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM