2014-11-04 64 views
2

我通过HttpResponseException从WebApi返回自定义异常。例如:从Web Api反序列化自定义异常

//Base class for all custom app exceptions 
public class MyAppException : Exception {} 

//Custom exceptions 
public class MyCustomException1 : MyAppException { //custom properties} 
public class MyCustomException2 : MyAppException { //other custom properties} 

客户端是HttpClient的,消息返回看起来是这样的:

{"Message":"An error has occurred.","ExceptionMessage":"Exception of type 'MyApp.Exceptions.MyCustomException1 ' was thrown.","ExceptionType":"MyApp.Exceptions.MyCustomException1 ","StackTrace":null} 

这里有2个问题:

  1. 的属性自定义异常的不在消息中
  2. 响应消息不能被反序列化为自定义异常

有没有办法将消息反序列化为正确的异常?

+0

您可以创建自己的自定义转换器(带Newtonsoft JSON)是在解串'ExceptionType'财产例外筑底看一看。 – 2014-11-04 09:42:56

回答

0

使用Custom model binder来分析ExceptionType属性以创建适当异常的实例。 请在这个工作Github sample

EDITED

+0

我想将反应消息反序列化为我的一个自定义异常。 – 2014-11-04 10:12:11

+0

对不起,误解了你的问题,编辑答案,请看看 – 2014-11-04 10:35:30