gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:21:50 25 4
gpt4 key购买 nike

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

如果我的“服务”抛出异常,我想使用 JSON 将该异常通过管道传回到 Web API。然后我想将异常反序列化回异常对象并抛出它。

我的代码:

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

public class ConnectionErrorException : Exception
{
public ConnectionErrorException()
{
}
public ConnectionErrorException(String message)
: base(message)
{
}
}

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

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

所以在这里我返回一个 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;
}

现在在这里,如果响应成功,我只返回字符串内容。如果请求失败,我会尝试将 json 响应传递给异常。但是我必须将它传递给基本异常,因为我还不知道它是什么类型。但是,当我调试并在异常上添加看门狗时。有一个参数 _className 表示“Domain.Model.Exceptions.API.ConnectionErrorException”。

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

这是为 ConnectionErrorException 返回的 json 示例:

{
"ClassName": "Domain.Model.Exceptions.API.ConnectionErrorException",
"Message": null,
"Data": null,
"InnerException": null,
"HelpURL": null,
"StackTraceString": "",
"HResult": -2146233088,
"Source": "LinkProvider.Logic",
"WatsonBuckets": null
}

最佳答案

用以下代码块替换您的异常处理。

else
{
var response = await response.Content.ReadAsStringAsync();
var exception = JsonConvert.DeserializeObject<Exception>(response);
// your handling logic here
Console.WriteLine(exception);
}

因此,如果服务抛出 new NotImplementedException("I haz error!"),上面将打印出 System.NotImplementedException: I haz error!


这是一个使用 MVVMLightJSON.net 的快速独立示例。假设您有 sender 作为

public class Sender
{
public Sender()
{
Messenger.Default.Register<NotificationMessage>(this, message =>
{
if ((Type)message.Target == typeof(Sender))
GotResponse(message.Notification);
});
}

public void SendRequest(string request)
{
Console.WriteLine("sending:{0}", request);
Messenger.Default.Send(
new NotificationMessage(this, typeof(Receiver), request));
}

private void GotResponse(string response)
{
Console.WriteLine("received:{0}", response);
if (response.Equals("ok"))
return;

Exception exception = JsonConvert.DeserializeObject<Exception>(response);
Console.WriteLine("exception:{0}", exception);

try
{
throw exception;
}
catch (Exception e)
{
Console.WriteLine("Indeed, it was {0}", e);
}
}
}

接收者作为

public class Receiver
{
public Receiver()
{
Messenger.Default.Register<NotificationMessage>(this, message =>
{
if ((Type)message.Target == typeof(Receiver))
GotRequest(message.Notification);
});
}

public void SendResponse(string response)
{
Messenger.Default.Send(new NotificationMessage(this, typeof(Sender), response));
}

public void GotRequest(string request)
{
string response = !string.IsNullOrWhiteSpace(request) ?
"ok" :
JsonConvert.SerializeObject(new NotImplementedException("I haz error!"));

SendResponse(response);
}
}

然后在“激活”之后

var sender = new Sender();
var receiver = new Receiver();
sender.SendRequest("my request");
sender.SendRequest(null);

打印出来

sending:my request
received:ok

sending:
received: {"ClassName":"System.NotImplementedException", "Message":"...","WatsonBuckets":null}

exception:System.NotImplementedException: I haz error!

Indeed, it was System.NotImplementedException: I haz error! at WpfApplication1.View.Sender.GotResponse(String response) in...

关于c# - 使用 JSON 在两个 C# 程序之间传递异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30210592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com