2014-06-17 25 views
4

這是用來捕捉web api中的異常 - 我應該使用try-catch語句嗎?

[RequestExceptionFilter] 
public class RequestController : ApiController 
{ 
    public IHttpActionResult Post([FromBody]Request RequestDTO) 
    { 
     //some code over here 
     throw new DTONullException(typeof(Request.Models.DTO.Request)); 

樣本ApiController這是我custom exception handler

public class RequestExceptionFilterAttribute : ExceptionFilterAttribute 
    { 
     public override void OnException(HttpActionExecutedContext context) 
     { 
      if (context.Exception is DTONullException) 
      { 
       context.Response = new HttpResponseMessage(HttpStatusCode.BadRequest) 
       { 
        Content = new StringContent("DTO is null"), 
        ReasonPhrase = "DTO is null", 
       }; 
      } 

      base.OnException(context); 
     } 
    } 

而且在調試時,我得到這個錯誤:

An exception of type 'Request.Controllers.DTONullException' occurred in Request.dll but was not handled in user code

enter image description here

我應該在這裏使用try-catch語法嗎?什麼是約定?

在我在互聯網上看到的所有樣本中,人們只是throw the exception,但他們似乎沒有抓住它。

(Ofcourse,如果我按Run,應用程序返回的預期BadRequest但問題是我應該使用try-catch或只留下上面的代碼,因爲這樣?)

+0

'基於答案below'和'http://stackoverflow.com/questions/58380/avoiding-first-chance-exception - 當異常被安全處理時,這是一種正常行爲。 –

+0

除此之外,爲了更深入地理解,我還引用了'http:// stackoverflow.com/questions/12519561/asp-net-web-api-throw-httpresponseexception-or-return-request-createerrorrespon'。 –

回答

3

在ASP捕捉異常的唯一可靠的方法.NET(無論您使用的是WebForms/MVC/WebApi)是global.asax中的Application_Error事件。

但是,您演示的例外可以通過IExceptionHandler來捕獲。

class OopsExceptionHandler : ExceptionHandler 
{ 
    public override void HandleCore(ExceptionHandlerContext context) 
    { 
     context.Result = new TextPlainErrorResult 
     { 
      Request = context.ExceptionContext.Request, 
      Content = "Oops! Sorry! Something went wrong." + 
         "Please contact [email protected] so we can try to fix it." 
     }; 
    } 

    private class TextPlainErrorResult : IHttpActionResult 
    { 
     public HttpRequestMessage Request { get; set; } 

     public string Content { get; set; } 

     public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) 
     { 
      HttpResponseMessage response = 
          new HttpResponseMessage(HttpStatusCode.InternalServerError); 
      response.Content = new StringContent(Content); 
      response.RequestMessage = Request; 
      return Task.FromResult(response); 
     } 
    } 
} 

,並在您webapi2配置添加以下內容:

config.Services.Replace(typeof(IExceptionHandler), new OopsExceptionHandler()); 
+1

謝謝。但我認爲這個問題不同。我問'如何拋出異常'。我已經實現了「自定義異常」,「異常過濾器屬性」。問題是,「使用throw語句拋出異常就足夠了嗎? (我問這是因爲我收到一個錯誤,「在用戶代碼中不處理異常」,如屏幕截圖所示) –

+1

您不必使用try/catch – jgauffin

+0

因此,調試期間出現錯誤?我可以跳過那個錯誤。正確嗎? –