2013-10-14 62 views
2

無論如何,我們可以得到HttpStatus代碼時捕獲異常?例外情況可能是Bad Request,408 Request Timeout,419 Authentication Timeout?如何在異常塊中處理這個問題?如何從WebAPI中的異常中獲取HttpStatusCode?

catch (Exception exception) 
      { 
       techDisciplines = new TechDisciplines { Status = "Error", Error = exception.Message }; 
       return this.Request.CreateResponse<TechDisciplines>(
       HttpStatusCode.BadRequest, techDisciplines); 
      } 
+1

-1這明顯是生成HttpResponses的代碼。不處理它們。 – Aron

回答

1

我在我的WebAPI控制器中進行錯誤處理時陷入了同樣的陷阱。我做了一些關於異常處理的最佳實踐的研究,並最終以下面的東西作爲一個魅力工作(希望它會幫助:)

try 
{  
    // if (something bad happens in my code) 
    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("custom error message here") }); 
} 
catch (HttpResponseException) 
{ 
    // just rethrows exception to API caller 
    throw; 
} 
catch (Exception x) 
{ 
    // casts and formats general exceptions HttpResponseException so that it behaves like true Http error response with general status code 500 InternalServerError 
    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(x.Message) }); 
} 
相關問題