2017-03-29 15 views
1

例外を処理する方法のパターンを探しています。具体的には、Web APIコントローラーから例外メッセージをクライアントに渡すことができるようにしたいと考えています。Web APIとAngular 2クライアントの間のエラー処理

私の現在のコールバック関数は、単にエラー上のライブラリよう

errorComplete(event: any) { 
    console.log("upload error"); 
} 

予告です

this.msgs = []; 
let xhr = new XMLHttpRequest(), 
formData = new FormData(); 


for(let i = 0; i < this.files.length; i++) { 
    formData.append(this.name, this.files[i], this.files[i].name); 
} 

xhr.upload.addEventListener('progress', (e: ProgressEvent) => { 
    if(e.lengthComputable) { 
     this.progress = Math.round((e.loaded * 100)/e.total); 
    } 
    }, false); 

xhr.onreadystatechange =() => { 
    if(xhr.readyState == 4) { 
     this.progress = 0; 

     if(xhr.status == 200) 
      this.onUpload.emit({xhr: xhr, files: this.files}); 
     else 
      this.onError.emit({xhr: xhr, files: this.files}); 

     this.clear(); 
    } 
}; 

xhr.open('POST', this.url, true); 
xhr.send(formData); 

として、クライアントはAPI に呼び出しを扱うサードパーティのライブラリを使用していますXMLHttpRequestをラップし、コールバック関数に渡します。

よう

throw new Exception("This is a test message"); 

これは予期しない例外を

をシミュレートすることであるが、以下のようにIは、テストラインが作成されているコントローラに現在のXMLHttpRequestでリターンコードが500であり、テキストがHTMLであります例外が発生すると.Netが生成されます。

はい私のコントローラのメソッドはtry-catchでラッパーする必要がありますが、私はクライアントにエラーメッセージを送信できるので、それを処理することができますし、catchするためにどのコードを入れるのか分かりませんアプリケーションを停止します。

私が見ている現在のユースケースは、ユーザーがファイルをシステムにアップロードしていますが、システムに指定された名前のファイルが既に存在することです。ファイルの名前を変更することはオプションではありません。その名前のファイルが既にシステムにあることをユーザーに通知する必要があります。

グーグルは私が処理できるようにメッセージを返信する方法を明らかにしていません。

+0

コントローラでtry catchを使用しないでください。 ExceptionHandler派生クラスを使用してクロスカットの問題を使用します。そのクラスでエラーコードと本文が返されます。通常500内部サーバーエラー。本文には、アプリ固有の詳細情報 – Nkosi

答えて

1

ありがとうございましたNkosi-あなたのコメントは正しい軌道に乗っています。 ミドルウェアを実装しました。

public class UIExceptionHandler 
{ 
    RequestDelegate _next; 
    public UIExceptionHandler(RequestDelegate next) 
    { 
     this._next = next; 
    } 

    public async Task Invoke(HttpContext context) 
    { 
     try 
     { 
      await this._next(context); 
     } 
     catch (Exception x) 
     { 
      if (!context.Response.HasStarted) 
      { 
       context.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; 
       context.Response.Headers["Message"] = x.Message; 
      } 
     } 
    } 
} 

public static class UIExcetionHandlerExtensions 
{ 
    public static IApplicationBuilder UseUIExceptionHandler(this IApplicationBuilder builder) 
    { 
     return builder.UseMiddleware<UIExceptionHandler>(); 
    } 
} 

とスタートアップのconfigureメソッドで

app.UseUIExceptionHandler(); 

その後、クライアント上の私は、誰もがこの解決策で問題を見れば、私は

を教えてください

errorComplete(event: any) { 
    var errorMessage = event.xhr.getResponseHeader('Message'); 
    console.log(errorMessage); 
} 

を行うことができます

関連する問題