使用JSON在两个C#程序之间传递异常

Zap*_*ica 5 c# json exception json.net asp.net-web-api

我有一个Web API,它向执行某些任务/命令的Windows服务发出HTTP请求.

如果我的'service'抛出异常,那么我想使用JSON将该异常传递回Web API.然后我想将异常反序列化回异常对象并抛出它.

我的代码:

Web API和服务之间的共享异常:

public class ConnectionErrorException : Exception
{
    public ConnectionErrorException()
    {
    }
    public ConnectionErrorException(String message)
        : base(message)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

现在在我的服务中,我有以下代码:

       ... 
       try
        {
            result = await ExecuteCommand(userId);
            //If reached here nothing went wrong, so can return an OK result
            await p.WriteSuccessAsync();
        }
        catch (Exception e)
        {
            //Some thing went wrong. Return the error so they know what the issue is
            result = e;
            p.WriteFailure();
        }
        //Write the body of the response:

        //If the result is null there is no need to send any body, the 200 or 400 header is sufficient
        if (result != null)
        {
            var resultOutput = JsonConvert.SerializeObject(result);
            await p.OutputStream.WriteAsync(resultOutput);
        }
        ...
Run Code Online (Sandbox Code Playgroud)

所以在这里我返回一个JSON对象.实际的响应对象,或者恰好发生的异常.

然后,这里是Web API中的代码,它向服务发出请求:

  // Make request
            HttpResponseMessage response = await client.PostAsJsonAsync(((int)(command.CommandId)).ToString(), command);
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
            else
            {
                var exception = HandleErrorResponse(await response.Content.ReadAsStringAsync());
                var type = exception.GetType();
                //TODO: try and determine which exact exception it is.
                throw exception;
            }
Run Code Online (Sandbox Code Playgroud)

现在,如果响应成功,我只返回字符串内容.如果请求失败,我尝试将json响应传递给异常.但是我必须像往常一样将它传递给基本异常 - 不知道它到底是什么类型.但是当我调试并在异常上添加一个看门狗时.有一个参数_className说明'Domain.Model.Exceptions.API.ConnectionErrorException`.

问题: 如何确定返回了哪个异常并将其反序列化为正确的异常,以便我可以再次抛出它.我需要知道确切的异常类型,因为我在Web API的服务层中处理了所有不同的异常.

以下是为以下内容返回的json示例ConnectionErrorException:

{
    "ClassName": "Domain.Model.Exceptions.API.ConnectionErrorException",
    "Message": null,
    "Data": null,
    "InnerException": null,
    "HelpURL": null,
    "StackTraceString": "",
    "HResult": -2146233088,
    "Source": "LinkProvider.Logic",
    "WatsonBuckets": null
}
Run Code Online (Sandbox Code Playgroud)

Ami*_*nul 1

您可以保留 C#dynamic对象的例外,然后将其序列化为 JSON,然后从 Windows 服务返回它。再次在 Web API 上,您反序列化该 JSON 并保留为动态对象。这样您就不必担心异常的实际类型。如有任何例外,您可以将其扔掉。如果您想知道异常的实际类型,那么您可以编写如下代码,反序列化后tempData对象在哪里dynamic

Type exceptionType = ((ObjectHandle)tempData).Unwrap().GetType();
Run Code Online (Sandbox Code Playgroud)

然后对异常进行相应的处理

希望这可以帮助 :)