2016-07-02 71 views
0

給定這樣的異常過濾器。WebApi2過濾器的默認異常對象

public override void OnException(HttpActionExecutedContext context) 
    { 
     var resp = new HttpResponseMessage(HttpStatusCode.InternalServerError) 
     { 
      // what must I change here to return an object 
      // similar to the default exception handler? 
      Content = new StringContent("THIS IS MY ERROR"), 
     }; 
     throw new HttpResponseException(resp); 
    } 

例外原因返回給客戶端的JavaScript 是一個普通字符串

當異常在默認WebApi2控制器被拋出,默認原因對象返回的包含配置,數據,標題等。我無法找到如何從異常過濾器返回所有這些額外信息的示例。我試圖檢查出的源無濟於事......

enter image description here

$http.get('/mydata') 
    .catch(function(reason) { ... do stuff with reason }) 
    .then(...); 

我需要什麼才能返回相同的默認響應,而不僅僅是一個簡單的字符串來改變。

Content = new ... // what goes here. 
+0

我沒有確切的代碼與我,但我已經做了幾次。你需要返回一個'IHttpActionResult'。有了這個,你可以發送你的HTTP狀態代碼500,400,401,403等。 –

+0

非常感謝:費馬會很自豪 – Jim

回答

0

給有此特定問題的任何人。

public override void OnException(HttpActionExecutedContext context) 
{ 
    var exception = context.Exception as DbEntityValidationException; 
    if (exception == null) 
     return; 

    var errors = exception.EntityValidationErrors.SelectMany(_ => _.ValidationErrors); 
    var messages = errors.Select(_ => Culture.Current($"{_.PropertyName}:{_.ErrorMessage}")); 
    var message = Culture.Current($"{context.Exception.Message}<br/>{string.Join("<br/>", messages)}"); 

    // create an error response containing all the required detail... 
    var response = context.Request.CreateErrorResponse(
     HttpStatusCode.InternalServerError, 
     message, 
     exception); 
    throw new HttpResponseException(response); 
} 
0

你沒有收到錯誤信息的原因是你的HttpResponseMessage不包含它。
所以你需要將它添加到對象輸入反應

 
    public override void OnException(HttpActionExecutedContext context) 
     { 
      if (context.Exception is NotImplementedException) 
      { 
       context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented); 
      } 
     } 

,並在你的行動,你扔NotImplementedException異常

[NotImplExceptionFilter] 
    public Contact GetContact(int id) 
    { 
     throw new NotImplementedException("This method is not implemented"); 
    } 

希望它能幫助。

+1

它並沒有真正幫助解釋JavaScript數據對象如何返回給客戶端在默認的IHttpActionResult中 – Jim