【发布时间】:2015-07-24 11:47:07
【问题描述】:
我有一个 Web API,它向执行某些任务/命令的 Windows 服务发出 HTTP 请求。
如果我的“服务”抛出异常,我想使用 JSON 将该异常通过管道传回 Web API。然后我想将异常反序列化回异常对象并抛出它。
我的代码:
Web API 和 Service 之间的共享异常:
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
}
【问题讨论】:
标签: c# json exception asp.net-web-api json.net