2017-03-29 82 views
1

所以我正在尋找一個關於如何處理異常的模式。具體而言,我希望能夠通過Web API控制器將異常消息傳遞給客戶端。Web api和角度2客戶端之間的錯誤處理

的客戶端使用第三方庫,以作爲

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 呼叫涉及這樣

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

通知,對錯誤的圖書館剛包裝XMLHttpRequest並將其傳遞給我的回調函數。

所以在控制我創建了一個測試線如下

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

這是模擬一個意外的異常

目前在XMLHttpRequest的返回代碼是500,文本是HTML .Net在發生異常時生成。

yes我的控制器中的方法需要包裝在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>(); 
    } 
} 

,並在啓動時的配置方法

app.UseUIExceptionHandler(); 

然後在客戶端上我可以做

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

如果有人看到一個問題,這個解決方案,請讓我知道