在this asp.net article中正確回答了全局錯誤處理。然而,這些文章缺少一些重要的觀點來讓代碼真正起作用。
本文涵蓋的細節,但在這裏它是在一個概括地說:
處理已經包含在System.Web.Http.ExceptionHandling
文章中的類是已經在這個庫中,所以沒有必要全局誤差重寫它們。
您需要編寫的唯一類是爲您的應用程序定製的類。在文章中,他們將其稱爲「OopsExceptionHandler」。但是,文章中編寫的那個不會編譯。這是更新的代碼,做工作:
public class OopsExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
context.Result = new TextPlainErrorResult
{
//If you want to return the actual error message
//Content = context.Exception.Message
Request = context.ExceptionContext.Request,
Content = "Oops! Sorry! Something went wrong." +
"Please contact [email protected] 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);
}
}
}
然後,您需要註冊的ExceptionHandler。這樣的例子並不在文章中給出的,所以在這裏它是:
config.Services.Replace(typeof(IExceptionHandler), new OopsExceptionHandler());
這行雲在WebApiConfig文件,寄存器方法。請注意,它使用'替換'而不是'添加',因爲它會在添加時出錯。框架只允許有一個。
這就是所有需要的。要測試,請從您的Web API中引發錯誤,您將看到作爲webAPI調用內容返回的錯誤消息。請注意,將錯誤消息返回給客戶端存在安全隱患,因此請確保這是您真正想要的。