これを行うには、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
}
}