我使用 ExceptionFilter 来执行此操作:
/// <summary>
/// Formats uncaught exception in a common way, including preserving requested Content-Type
/// </summary>
public class FormatExceptionsFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
Exception exception = actionExecutedContext.Exception;
if (exception != null)
{
HttpRequestMessage request = actionExecutedContext.Request;
// we shouldn't be getting unhandled exceptions
string msg = "Uncaught exception while processing request {0}: {1}";
AspLog.Error(msg.Fmt(request.GetCorrelationId().ToString("N"), exception), this);
// common errror format, without sending stack dump to the client
HttpError error = new HttpError(exception.Message);
HttpResponseMessage newResponse = request.CreateErrorResponse(
HttpStatusCode.InternalServerError,
error);
actionExecutedContext.Response = newResponse;
}
}
}
它是这样注册的:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new ApiControllers.FormatExceptionsFilterAttribute());
// other stuff
}
}