2016-04-04 64 views
0

我想在web API中实现自定义异常处理。发送类对象到异常处理

我能够实现一些初始实现,但我想传递类对象到异常来显示所有属性。像

class error 
    { 
     int error_code 
     string error_message 
     string API 
    } 

当某些错误发生它应该显示JSON像

{ 
"error_code": 0, 
"error_message":"Either Your are not authorized or you don't have any project yet.", 
"API": "save data" 
} 

此代码只显示消息

throw new HttpResponseException(
         Request.CreateErrorResponse(HttpStatusCode.NotFound, message)); 

任何建议,

感谢

回答

1

你菊st需要给你的对象作为CreateResponse方法的输入。产生错误响应如下,

return Request.CreateResponse(HttpStatusCode.BadRequest, error, 
    new System.Net.Http.Headers.MediaTypeHeaderValue("application/json")); 

的网络API会自动JSON-外商投资企业传递了error对象。
确保在执行此操作之前在error对象中设置了必要的值。
希望这会有所帮助。

编辑
设置你的HttpStatusCode作为BadRequest而不是NotFound因为你产生异常。这是更合适的。

+0

谢谢......它的工作原理 –