C# 捕获web api中的异常-我应该使用try-catch语句吗?
这是一个使用的示例C# 捕获web api中的异常-我应该使用try-catch语句吗?,c#,.net,exception,asp.net-web-api,asp.net-web-api2,C#,.net,Exception,Asp.net Web Api,Asp.net Web Api2,这是一个使用的示例ApiController [RequestExceptionFilter] public class RequestController : ApiController { public IHttpActionResult Post([FromBody]Request RequestDTO) { //some code over here throw new DTONullException(typeof(Request.Mod
ApiController
[RequestExceptionFilter]
public class RequestController : ApiController
{
public IHttpActionResult Post([FromBody]Request RequestDTO)
{
//some code over here
throw new DTONullException(typeof(Request.Models.DTO.Request));
这是我的自定义异常处理程序
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);
}
}
在调试过程中,我遇到以下错误:
Request.dll中发生了“Request.Controllers.DTONullException”类型的异常,但未在用户代码中处理该异常
我应该在这里使用try-catch
语法吗?什么是公约
在我在互联网上看到的所有示例中,人们只是抛出异常
,但他们似乎没有捕捉到它
(当然,如果我按
Run
,应用程序会按预期返回一个BadRequest
,但问题是我应该使用try catch
,还是只保留上面的代码?在ASP.NET中捕获异常的唯一可靠方法(无论您使用的是WebForms/MVC/WebApi)是global.asax中的事件
但是,您演示的异常可能会被捕获
非常感谢。但我认为问题是不同的。我在问
如何抛出异常
。我已经实现了一个自定义异常
,一个异常过滤器属性
。问题是,使用throw语句抛出异常是否足够?(我问这个问题是因为我收到一个错误“用户代码中未处理异常,如屏幕截图中所示”)您不必使用try/catch。因此,在调试期间出现错误是可以的?我可以跳过那个错误。正确吗?是的,按F5,您的处理程序将处理它。它被称为第一次机会异常,是一种调试功能。基于下面的答案
和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
了解更多信息。
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 support@contoso.com 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);
}
}
}
config.Services.Replace(typeof(IExceptionHandler), new OopsExceptionHandler());