typescript 异步/等待尝试捕获错误处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47404319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:03:00  来源:igfitidea点击:

Async / Await Try Catch Error Handling

angulartypescript

提问by Ryan Buening

I'm using the JSONPlaceholder API: https://jsonplaceholder.typicode.com. I have the following in my service.ts:

我正在使用 JSONPlaceholder API:https://jsonplaceholder.typicode.com 。我有以下内容service.ts

public async getPosts(): Promise<Post[]> {
    try {
        const response = await this._http.get<Post[]>(this._baseUrl + "api/JsonPlaceholder/GetPosts");
        return response.toPromise();
    } catch (error) {
        await this.handleError(error);
    }
}

Which I try to use in my component.ts:

我尝试在我的component.ts

public posts: Post[];

public async ngOnInit() {
    const posts = await this._placeholderService.getPosts();
    this.posts = posts;
}

However, the TypeScript compiler throws an error on public async getPosts(): Promise<Post[]>- Function lacks ending return statement and return type does not include 'undefined'.

但是,TypeScript 编译器会在以下方面引发错误public async getPosts(): Promise<Post[]>-Function lacks ending return statement and return type does not include 'undefined'.

It is expecting a return statement in either the catch block or outside the try-catch. What is best practice for handling errors like this when I want to return a specific type...in my case Post[]. Is there a better way to structure these types of calls?

它期待在 catch 块中或在 try-catch 之外的 return 语句。当我想返回特定类型时,处理此类错误的最佳做法是什么......在我的情况下Post[]。有没有更好的方法来构建这些类型的调用?

回答by Aaron Beall

What does handleErrordo? What do you want to happen when the http request fails? Right now you are swallowing the error and returning undefined. You could fix your return type annotation as Promise<Post[] | undefined>(or remove it which will infer that type), then you need to handle the undefinedcase in upstream code:

有什么作用handleError?当http请求失败时,您希望发生什么?现在您正在吞下错误并返回undefined. 您可以将您的返回类型注释修复为Promise<Post[] | undefined>(或删除它以推断该类型),然后您需要undefined在上游代码中处理这种情况:

public async ngOnInit() {
    const posts = await this._placeholderService.getPosts();
    if (posts) {
        this.posts = posts;
    } else {
        this.errorMessage = "Failed to load posts!";
    }
}

Or you could just return []if you aren't handling the error case anyway:

或者,return []如果您无论如何都不处理错误情况,您也可以:

} catch (error) {
    await this.handleError(error);
    return [];
}

Or you could throw the error and allow upstream code to handle it or not:

或者您可以抛出错误并允许上游代码处理它或不处理它:

} catch (error) {
    await this.handleError(error);
    throw error;
}

public async ngOnInit() {
    try {
        const posts = await this._placeholderService.getPosts();
        this.posts = posts;
    } catch(error) {
        // Note that 'error' could be almost anything: http error, parsing error, type error in getPosts(), handling error in above code
        this.errorMessage = "Failed to load posts!";
    }
}

回答by basarat

It is expecting a return statement in either the catch block or outside the try-catch. What is best practice for handling errors like this when I want to return a specific type...in my case Post[]. Is there a better way to structure these types of calls?

它期待在 catch 块中或在 try-catch 之外的 return 语句。当我想返回特定类型时,处理此类错误的最佳做法是什么……在我的情况下是 Post[]。有没有更好的方法来构建这些类型的调用?

Simple annotation to reflect the true nature of the code you have written:

简单的注释来反映您所编写代码的真实性质:

public async getPosts(): Promise<Post[] | undefined> { // notice `undefined`
    try {
        const response = await this._http.get<Post[]>(this._baseUrl + "api/JsonPlaceholder/GetPosts");
        return response.toPromise();
    } catch (error) {
        await this.handleError(error);
    }
}

TypeScript is just pointing out this truth for you

TypeScript 只是为你指出了这个事实