在 Web API 中返回自定义错误对象 [英] Return custom error objects in Web API

查看:29
本文介绍了在 Web API 中返回自定义错误对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MVC 4 Web API 框架开发一个 Web API.如果有异常,我目前正在抛出一个新的 HttpResponseException.即:

I have a web API I'm working on using the MVC 4 Web API framework. If there is an exception, I'm currently throwing a new HttpResponseException. ie:

if (!Int32.TryParse(id, out userId))
    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid id")); 

这会向客户端返回一个对象,该对象只是 {"message":"Invalid id"}

This returns an object to the client that is simply {"message":"Invalid id"}

我想通过返回更详细的对象来进一步控制对异常的响应.类似的东西

I would like to gain further control over this response to exceptions by returning a more detailed object. Something like

{
 "status":-1,
 "substatus":3,
 "message":"Could not find user"
 }

我该怎么做?序列化我的错误对象并将其设置在响应消息中的最佳方法是什么?

How would I go about doing this? Is the best way to serialize my error object and set it in the response message?

我还稍微研究了 ModelStateDictionary 并提出了这一点黑客",但它仍然不是一个干净的输出:

I've also looked into the ModelStateDictionary a bit and have come up with this bit of a "hack", but it's still not a clean output:

var msd = new ModelStateDictionary();
msd.AddModelError("status", "-1");
msd.AddModelError("substatus", "3");
msd.AddModelError("message", "invalid stuff");
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, msd));

编辑
看起来像我需要的自定义 HttpError .这似乎可以解决问题,现在让它可以从我的业务层扩展......

edit
looks like a custom HttpError is what I need. This seems to do the trick, now to make it extensible from my business layer...

var error = new HttpError("invalid stuff") {{"status", -1}, {"substatus", 3}};
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, error));

推荐答案

我认为这可以解决问题:

I think this will do the trick:

为业务层创建自定义异常类:

Create a custom exception class for the business layer:

 public class MyException: Exception
 {
    public ResponseStatus Status { get; private set; }
    public ResponseSubStatus SubStatus { get; private set; }
    public new string Message { get; private set; }

    public MyException()
    {}

    public MyException(ResponseStatus status, ResponseSubStatus subStatus, string message)
    {
        Status = status;
        SubStatus = subStatus;
        Message = message;
    }
 }

创建一个静态方法以从 MyException 的实例生成 HttpError.我在这里使用反射,所以我可以将属性添加到 MyException 并且总是在不更新 Create 的情况下返回它们:

Create a static method to generate a HttpError from an instance of MyException. I'm using reflection here so I can add properties to MyException and always have them returned w/o updating Create:

    public static HttpError Create<T>(MyException exception) where T:Exception
    {
        var properties = exception.GetType().GetProperties(BindingFlags.Instance 
                                                         | BindingFlags.Public 
                                                         | BindingFlags.DeclaredOnly);
        var error = new HttpError();
        foreach (var propertyInfo in properties)
        {
            error.Add(propertyInfo.Name, propertyInfo.GetValue(exception, null));
        }
        return error;
    }

我目前有一个通用异常处理程序的自定义属性.MyException 类型的所有异常都将在此处处理:

I currently have a custom attribute for a general exception handler. All exceptions of type MyException will be handled here:

public class ExceptionHandlingAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        var statusCode = HttpStatusCode.InternalServerError;

        if (context.Exception is MyException)
        {
            statusCode = HttpStatusCode.BadRequest;
            throw new HttpResponseException(context.Request.CreateErrorResponse(statusCode, HttpErrorHelper.Create(context.Exception)));
        }

        if (context.Exception is AuthenticationException)
            statusCode = HttpStatusCode.Forbidden;

        throw new HttpResponseException(context.Request.CreateErrorResponse(statusCode, context.Exception.Message));
    }
}

当我发现这个计划中的漏洞时,我会多玩一点并更新.

I'll play around with this a bit more and update as I find holes in this plan.

这篇关于在 Web API 中返回自定义错误对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆