过滤器的 WebApi2 默认异常 object

WebApi2 default exception object for filter

给定这样的异常过滤器。

    public override void OnException(HttpActionExecutedContext context)
    {
        var resp = new HttpResponseMessage(HttpStatusCode.InternalServerError)
        {
            // what must I change here to return an object
            // similar to the default exception handler?
            Content = new StringContent("THIS IS MY ERROR"),
        };
        throw new HttpResponseException(resp);
    }

发送给客户端的异常原因returnjavascript是一个纯字符串.

当在defaultWebApi2控制器中抛出异常时,默认原因objectreturned 包含配置、数据、headers 等。我找不到如何从我的异常过滤器中 return 所有这些额外信息的示例。我尝试查看源代码无济于事...

 $http.get('/mydata')
     .catch(function(reason) { ... do stuff with reason })
     .then(...);

What do I need to change in order to return the same default response rather than just a plain string.

Content = new ... // what goes here.

您没有收到错误消息的原因是您的 HttpResponseMessage 不包含它。
所以你需要将它添加到响应对象

    public override void OnException(HttpActionExecutedContext context)
        {
            if (context.Exception is NotImplementedException)
            {
                context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
            }
        }

并且在您的操作中,您抛出了 NotImplementedException 异常

[NotImplExceptionFilter]
    public Contact GetContact(int id)
    {
        throw new NotImplementedException("This method is not implemented");
    }

希望对您有所帮助。

对于遇到此特定问题的任何其他人。

public override void OnException(HttpActionExecutedContext context)
{
    var exception = context.Exception as DbEntityValidationException;
    if (exception == null)
        return;

    var errors = exception.EntityValidationErrors.SelectMany(_ => _.ValidationErrors);
    var messages = errors.Select(_ => Culture.Current($"{_.PropertyName}:{_.ErrorMessage}"));
    var message = Culture.Current($"{context.Exception.Message}<br/>{string.Join("<br/>", messages)}");

    // create an error response containing all the required detail...
    var response = context.Request.CreateErrorResponse(
         HttpStatusCode.InternalServerError,
         message,
         exception);
    throw new HttpResponseException(response);
}
public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is NotSupportedException)
        {
            context.Response = context.Request.CreateErrorResponse(HttpStatusCode.BadRequest,
                JsonConvert.SerializeObject(new[] {context.Exception.Message}));
            return;
        }

        string exceptionMessage = null;
        // Validation Related Errors
        if (context.Exception is DbEntityValidationException)
        {
            var typedEx = context.Exception as DbEntityValidationException;
            if (typedEx == null)
                return;
            var errorMessages = typedEx.EntityValidationErrors
                .SelectMany(x => x.ValidationErrors)
                .Select(x => x.ErrorMessage);
            var fullErrorMessage = string.Join("; ", errorMessages);
            exceptionMessage = string.Concat(typedEx.Message, " The validation errors are: ", fullErrorMessage);
        }
        // All Global Exceptions
        var innerException = context.Exception.GetBaseException();
        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
        {
            Content = new StringContent(JsonConvert.SerializeObject(new
            {
                Data = new
                {
                    IsSuccess = false,
                    StatusCode = 45000,
                    ErrorMessage = exceptionMessage ??
                                   $"{innerException.Message} StackTrace : {innerException.StackTrace}"
                }
            })),
            ReasonPhrase = "Deadly Exception!"
        });
    }

ExceptionFilter 的工作示例。