WebApi2过滤器的默认异常对象

时间:2016-07-02 11:04:43

标签: c# webapi2

给出像这样的异常过滤器。

    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);
    }

原因异常返回给客户端javascript 是一个纯字符串

默认 WebApi2控制器中抛出异常时,返回的默认原因对象包含配置,数据,标题等。我无法找到如何从我的异常过滤器返回所有这些额外信息的示例。我试过检查来源无济于事......

enter image description here

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

为了返回相同的默认响应而不仅仅是一个普通字符串,我需要更改什么。

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

3 个答案:

答案 0 :(得分:0)

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

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

并在您的操作中,抛出NotImplementedException Exception

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

希望它有所帮助。

答案 1 :(得分:0)

对于有这个特殊问题的任何人。

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);
}

答案 2 :(得分:0)

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的工作示例。