如何在Web API中抛出异常? [英] How to throw exception in Web API?
本文介绍了如何在Web API中抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是我的代码:
public Test GetTestId(string id)
{
测试测试= _test.GetTest(id);
if(test == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
返回测试;
}
我不认为我做正确的事情,我的客户端知道这是一个 HTTP 404
错误?
解决方案
完全正确。
或者,如果您希望提供更多信息(允许,如您所说,客户端与常规404区分开):
if(test == null)
{
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound,
this item不存在));
}
How can I throw a exception to in ASP.net Web Api?
Below is my code:
public Test GetTestId(string id)
{
Test test = _test.GetTest(id);
if (test == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return test;
}
I don't think I am doing the right thing, How do my client know it is a HTTP 404
error?
解决方案
It's absolutely fine.
Alternatively, if you wish to provide more info (to allow, as you say, the client to distinguish from regular 404):
if (test == null)
{
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound,
"this item does not exist"));
}
这篇关于如何在Web API中抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文