【发布时间】:2014-08-07 13:03:21
【问题描述】:
这是一个示例ApiController 使用
[RequestExceptionFilter]
public class RequestController : ApiController
{
public IHttpActionResult Post([FromBody]Request RequestDTO)
{
//some code over here
throw new DTONullException(typeof(Request.Models.DTO.Request));
这是我的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,但他们似乎没有抓住它。
(当然,如果我按Run,应用程序会按预期返回BadRequest,但问题是我应该使用try-catch 还是只保留上面的代码?)
【问题讨论】:
-
Based on the answer below和http://stackoverflow.com/questions/58380/avoiding-first-chance-exception-messages-when-the-exception-is-safely-handled,这是正常行为。 -
除此之外,我还提到了
http://stackoverflow.com/questions/12519561/asp-net-web-api-throw-httpresponseexception-or-return-request-createerrorrespon,以便更深入地了解。
标签: c# .net exception asp.net-web-api asp.net-web-api2