将类对象发送到异常处理



我想在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));

任何建议,

感谢

您只需要将对象作为CreateResponse方法的输入。生成如下错误响应,

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

web API将自动对您传递的error对象进行实例化
执行此操作之前,请确保在error对象中设置了必要的值
希望这能有所帮助。

编辑
HttpStatusCode设置为BadRequest,而不是NotFound,因为您正在生成异常。这更合适。

最新更新