我正在使用web 2来为客户开发服务,管理我们正在使用的ExceptionsFilterAttribute错误,但正如您所知,在这个级别上并不是所有的例外都会被捕获。在protected void Application_AuthenticateRequest(Object sender, EventArgs e)中会引发一些错误,我希望处理这些错误并向我们的客户端发送一条自定义消息,以便向他提供有关错误的更多细节,为了解决这个问题,我创建了一个GlobalExceptionHandler
public class GlobalExceptionHandler: ExceptionHandler
{
//A basic DTO to return back to the caller with data about the error
private class ErrorInformation
{
public string Message { get; set; }
public DateTime ErrorDate { get; set; }
}
public override void Handle(ExceptionHandlerContext context)
{
//Return a DTO representing what happened
context.Result = new ResponseMessageResult(context.Request.CreateResponse(HttpStatusCode.InternalServerError,
new ErrorInformation { Message="We apologize but an unexpected error occured. Please try again later.", ErrorDate=DateTime.UtcNow }));
//This is commented out, but could also serve the purpose if you wanted to only return some text directly, rather than JSON that the front end will bind to.
//context.Result = new ResponseMessageResult(context.Request.CreateResponse(HttpStatusCode.InternalServerError, "We apologize but an unexpected error occured. Please try again later."));
}
}在WebApiConfig中,我添加了以下一行:
config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());Application_AuthenticateRequest会引发一些错误,但从未到达GlobalExceptionHandler。
你知道我怎么解决这个问题吗?
提前谢谢。
发布于 2017-05-05 20:12:49
Application_AuthenticateRequest没有出现在Web管道中。因此,如果在此方法中抛出异常,这些异常可以被Web异常处理程序捕获,因为异常是在Web管道启动之前抛出的。
有两种方法可以做到这一点:
- If this project has only Web API related controllers, not like MVC and all.
https://stackoverflow.com/questions/43803455
复制相似问题