這是用來捕捉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
我應該在這裏使用try-catch
語法嗎?什麼是約定?
在我在互聯網上看到的所有樣本中,人們只是throw the exception
,但他們似乎沒有抓住它。
(Ofcourse,如果我按Run
,應用程序返回的預期BadRequest
但問題是我應該使用try-catch
或只留下上面的代碼,因爲這樣?)
'基於答案below'和'http://stackoverflow.com/questions/58380/avoiding-first-chance-exception - 當異常被安全處理時,這是一種正常行爲。 –
除此之外,爲了更深入地理解,我還引用了'http:// stackoverflow.com/questions/12519561/asp-net-web-api-throw-httpresponseexception-or-return-request-createerrorrespon'。 –