简体   繁体   English

C#中具有未知异常类型的泛型类

[英]Class with generics for unknown exception type in c#

In my applications Web API , I have an exception filter that suppose to catch any exception and transmit it to the client within a response wrapper class. 在我的应用程序Web API ,我有一个异常过滤器,该异常过滤器想捕获任何异常并将其传输到响应包装器类中的客户端。 My goal is to make that exception transmit with the correct type, so the client can reconstruct and re-throw it. 我的目标是使异常以正确的类型传输,以便客户端可以重构并重新抛出该异常。

Following is the code for exception catcher: 以下是异常捕获器的代码:

public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {

        HttpStatusCode OutputHttpCode = HttpStatusCode.InternalServerError;
        var exceptionType = actionExecutedContext.Exception.GetType();

        if (exceptionType == typeof(InvalidIDException))
        {
            OutputHttpCode = HttpStatusCode.Unauthorized;
        }

        //this way of getting type didnt work for me either
        //var exceptionType = typeof(RestErrorResponse<>).MakeGenericType(actionExecutedContext.Exception.GetType());

        actionExecutedContext.Response = new HttpResponseMessage()
        {
            Content = new StringContent(JsonConvert.SerializeObject(
                //this will not compile here, saying t is a variable but used like a type.
                //If i use generic "Exception" instead everything is working fine,
                //but it will be interpreted as generic exception on client side and
                //could not be handled properly if i rethrow it directly
                new RestErrorResponse<exceptionType> () //Exception will compile
                {
                    Content = null,
                    Status = RestStatus.Error,
                    Exception = actionExecutedContext.Exception
                }
                ),
                    System.Text.Encoding.UTF8, "application/json"),

            StatusCode = OutputHttpCode
        };

        base.OnException(actionExecutedContext);
    }

This is a class with generics I'm trying to put my exception into: 这是一个具有泛型的类,我正在尝试将异常放入:

public class RestErrorResponse<E> :RestResponse<Object> {
    public E myException { get; set; }
}

If i use a generic Exception in my "RestErrorResponse" class this is a JSON that gets created: 如果我在“ RestErrorResponse”类中使用通用的Exception,则这是创建的JSON:

{
  "Exception": {
    "ClassName": "InvalidLoginException",
    "Message": "Invalid User Name",
    "Data": {},
    "InnerException": null,
    "HelpURL": null,
    "StackTraceString": "....",
    "RemoteStackTraceString": null,
    "RemoteStackIndex": 0,
    "ExceptionMethod": "....",
    "HResult": -2147024809,
    "Source": "DB",
    "WatsonBuckets": null,
    "ParamName": null
  },
  "Status": {
    "Verbal": "Error",
    "Code": 1074
  },
  "Content": null
}

My goal will be to get: 我的目标是获得:

{
  "InvalidLoginException": {
    "ClassName": "InvalidLoginException",
    "Message": "Invalid User Name",
    "Data": {},
    "InnerException": null,
    "HelpURL": null,
    "StackTraceString": "....",
    "RemoteStackTraceString": null,
    "RemoteStackIndex": 0,
    "ExceptionMethod": "....",
    "HResult": -2147024809,
    "Source": "DB",
    "WatsonBuckets": null,
    "ParamName": null
  },
  "Status": {
    "Verbal": "Error",
    "Code": 1074
  },
  "Content": null
}

Is RestErrorResponse a class under your control? RestErrorResponse是您所控制的类吗? If so, does it really have to be generic? 如果是这样,它真的必须是通用的吗? Consider this: 考虑一下:

public class RestErrorResponse : RestResponse<Object> {
    public object Exception { get; set; }
}

Now you can simply instantiate it: 现在您可以简单地实例化它:

var response = new RestErrorResponse 
{
     // other properties
     Exception = actionExecutedContext.Exception
}

If you can't change it, you will need reflection to create the instance of RestErrorResponse. 如果无法更改,则需要进行反射以创建RestErrorResponse实例。 For example: 例如:

 var responseType = typeof(RestErrorResponse<>).MakeGenericType(exceptionType);
 dynamic response = Activator.CreateIntance(type);
 response.Content = null;
 response.Status = RestStatus.Error;
 response.Exception = actionExecutedContext.Exception;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM