zoukankan      html  css  js  c++  java
  • REST服务中的异常处理

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

    HTTP/1.1 500 Internal Server Error
    Content-Length: 56
    Content-Type: text/xml; charset=utf-8
    Server: Microsoft-HTTPAPI/2.0
    Date: Tue, 14 Jul 2015 13:22:15 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/1.1 403 forbidden
    Content-Length: 35
    Content-Type: text/plain; charset=utf-8
    Server: Microsoft-HTTPAPI/2.0
    Date: Tue, 14 Jul 2015 13:26:38 GMT
    
    Not allowed to delete this resource
  • 相关阅读:
    swift学习-----字典
    Swift学习----数组
    Swift学习-----循环
    Swift学习-----可选类型
    Swift学习-----分支
    Swift学习------常量与变量
    autorelease,autoreleasepool基本使用
    SDWebImage缓存图片的机制(转)
    新闻网站项目django--分类页
    新闻网站项目django--首页
  • 原文地址:https://www.cnblogs.com/you-you-111/p/4646644.html
Copyright © 2011-2022 走看看