2017-11-21 16 views
0

私はJSONPlaceholder APIを使用しています:https://jsonplaceholder.typicode.com。私は私のservice.tsに次のようにありますAsync/Awaitキャッチエラー処理を試す

私は component.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); 
    } 
} 

public posts: Post[]; 

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

をしかし、活字体のコンパイラはpublic async getPosts(): Promise<Post[]>にエラーがスローされます - Function lacks ending return statement and return type does not include 'undefined'.

それは期待していますcatchブロックまたはtry-catchの外側にあるreturn文。私の場合、特定の型を返すときにこのようなエラーを処理するためのベストプラクティスは何ですか?Post[]。これらのタイプのコールを構造化するより良い方法はありますか?

答えて

3

handleErrorは何をするために、この真実を指摘していますか? httpリクエストが失敗したときに何をしたいですか?今、あなたはエラーを飲み込んで、undefinedを返しています。あなたは、あなたが上流のコードでundefinedケースを処理する必要があり、Promise<Post[] | undefined>としてあなたの戻り値の型注釈を修正(またはその型を推測しますそれを削除する)ことができます:

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

それとも、可能性だけでreturn []あなたが処理していない場合とにかくエラーの場合:

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

それとも、エラーをスローし、上流のコードはそれを扱うかどうかする可能性があります:

} 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!"; 
    } 
} 
+0

HTTPリクエストF私はユーザーに何らかの形で通知し、うまく失敗したい。現在、 'const response = await this._http.get (this._baseUrl +" api/JsonPlaceholder/GetPosts ");'が失敗した場合(URLエンドポイントが間違っているとします)、 'Uncaught(promise)'例外。 'const response'はステータスがない' Observable 'の型です。ステータスを得るためにこれをどのように構成しますか? –

+1

@RyanBueningあなたが投げたエラーを通すか、再投げて、ユーザにメッセージを表示して 'getPosts()'を呼び出そうとするところでそれを処理するように思えます。これを示すために最後の例を更新しました。 – Aaron

+0

これはうまくいくようです。私は以下を持っています:https://gist.github.com/ryanbuening/102d96807e5557e072d82f2b6f359384。このコードを間違ったエンドポイントで実行するページをロードすると、私のコンソールに500エラーが記録された警告「エラー!」が表示されます。しかし、私が再びリフレッシュすると、 'NodeInvocationException:Uncaught(promise):ReferenceError:alert is not defined'というメッセージが表示されます。なぜ私はそれを取得するだろうと警告のエラーメッセージではない知っていますか?サーバー側のレンダリングを使用して私と関係がありますか? (私はJavaScriptServices https://github.com/aspnet/JavaScriptServicesとASP.NETコアを使用しています) –

1

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?

簡単な注釈は、あなたが書いたコードの真の性質を反映します

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); 
    } 
} 

活字体はちょうどあなたが

関連する問題