我是一个全局异常处理程序类,以便处理我的异常:
namespace MyProject.Extensions
{
public class MyExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
context.Result = new MyErrorResult
{
Request = context.ExceptionContext.Request,
ContextException = context.Exception
};
}
}
private class MyErrorResult : IHttpActionResult
{
public HttpRequestMessage Request { get; set; }
public Exception ContextException { get; set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
HttpResponseMessage response = MyErrorResponse(Request, ContextException);
response.RequestMessage = Request;
return Task.FromResult(response);
}
}
}
然后在global.asax中注册它:
protected void Application_Start()
{
ConfigureLog4Net();
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
DependencyConfig.RegisterDependencies(GlobalConfiguration.Configuration);
GlobalConfiguration.Configuration.EnsureInitialized();
}
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Services.Replace(typeof(IExceptionHandler), new MyExceptionHandler());
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}",
defaults: new { action = RouteParameter.Optional }
);
}
}
当我在我的一个控制器中抛出测试异常时,Visual studio停止并发出错误'异常未处理'。我究竟做错了什么?任何帮助将不胜感激。