REST服务中的异常处理

在REST服务中,服务端如果产生了异常信息,无论是业务异常或是系统异常,如果直接将异常抛出,在客户端浏览器中,是无法获取异常的详细,只能获取一个StateCode 500 Internal Server Error错误,如下:

HTTP/ Internal Server Error
Content-Length:
Content-Type: text/xml; charset=utf-
Server: Microsoft-HTTPAPI/2.0
Date: Tue,  Jul  :: GMT

<Error><Message>An error has occurred.</Message></Error>

如需要在客户端获取服务端的详细异常信息,需要如下定义异常信息:

var resp = new HttpResponseMessage(HttpStatusCode.Forbidden)
{
    Content = new StringContent("Not allowed to delete this resource"),
    ReasonPhrase = "forbidden"
};
    throw new HttpResponseException(resp);

抛出HttpResponseException即可在客户端(浏览器,调试工具如Fiddler)中进行捕获并进行对应处理,如下所示:

HTTP/ forbidden
Content-Length:
Content-Type: text/plain; charset=utf-
Server: Microsoft-HTTPAPI/2.0
Date: Tue,  Jul  :: GMT

Not allowed to delete this resource
上一篇:Using Integrated SOA Gateway in Oracle EBS(websevice)


下一篇:Python接口自动化测试框架(实战篇)-- 数据驱动DDT