[英]Send class object to Exception Handling
我想在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
对象进行json-fies处理。
在执行此操作之前,请确保在error
对象中设置了必要的值。
希望这可以帮助。
编辑
设置你的HttpStatusCode
的BadRequest
,而不是NotFound
因为你产生异常。 比较合适
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.