2017-03-09 42 views
1

我正在使用Angular 1.5和ASP.Net WebApi 2.我想在$ http.get請求失敗時顯示錯誤消息。不幸的是,錯誤回調只包含一般狀態文本(例如內部服務器錯誤),但不包含我指定的消息。我怎樣才能達到目的?

網絡API控制器:

public IHttpActionResult GetSomething() 
{ 
    try 
    { 
    var result = new HttpResponseMessage(HttpStatusCode.OK); 
    result.Content = new ByteArrayContent(GetContent(...)); 
    return ResponseMessage(result); 
    } 
    catch (Exception ex) 
    { 
    return InternalServerError(ex); 
    } 
} 

角電話:

$http.get('url') 
.then(function (result) { 
...    
}, function (error) { 
    //$scope.errorMessage= ??? 
}); 

回答

0

您可以創建自己的結果,包括任何你想要的內容:

public class ServerErrorResult : HttpActionErrorResult 
{ 
    public Exception Exception {get; set;} 

    public override Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) 
    { 
     var content = Content; 
     if(Exception != null) 
     { 
      content += $"\r\nException Details:{Exception.Message}"; 
     } 
     var response = new HttpResponseMessage(HttpStatusCode.InternalServerError) 
     { 
      Content = new StringContent(content), 
      RequestMessage = Request; 
     }; 

     return Task.FromResult(response); 
    } 
} 

然後在你的控制器,你只需要返回這個新的結果:

public IHttpActionResult GetSomething() 
{ 
    try 
    { 
    var result = new HttpResponseMessage(HttpStatusCode.OK); 
    result.Content = new ByteArrayContent(GetContent(...)); 
    return ResponseMessage(result); 
    } 
    catch (Exception ex) 
    { 
    return new ServerErrorResult 
     { 
      Exception = ex 
     }; 
    } 
} 

您也可以在控制器上創建擴展方法來抽象一些這種管道走的:

public static HttpActionErrorResult ServerError(this ApiController controller, Exception ex) 
{ 
    return new ServerErrorResult 
     { 
      Exception = ex 
     }; 
} 

從你的控制器這樣稱呼它:

​​

希望幫助。