前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【翻译】ASP.NET WEB API异常处理

【翻译】ASP.NET WEB API异常处理

作者头像
liulun
发布2022-05-09 13:23:54
5220
发布2022-05-09 13:23:54
举报
文章被收录于专栏:liulunliulun

当一个web api抛出一个异常后

此异常会被转化成一个HTTP响应

错误代码为500的服务错误

但是如果你不想让客户端看到500的错误码

你也可以自定义错误码

如下代码当用户输入的ID没有与之相关的数据

则返回了错误码为404的错误

(页面未找到)

代码语言:javascript
复制
public Product GetProduct(int id) 
{ 
    Product item = repository.Get(id); 
    if (item == null) 
    { 
        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)); 
    } 
    return item; 
}

如果需要进一步自定义错误消息的内容

可以通过如下方法来完成

代码语言:javascript
复制
public Product GetProduct(int id) 
{ 
    Product item = repository.Get(id); 
    if (item == null) 
    { 
        var resp = new HttpResponseMessage(HttpStatusCode.NotFound) 
        { 
            Content = new StringContent(string.Format("No product with ID = {0}", id)), 
            ReasonPhrase = "Product ID Not Found" 
        } 
        throw new HttpResponseException(resp); 
    } 
    return item; 
}

结果如下图所示

image
image
image
image

另外

开发人员可以托管异常的抛出

异常过滤器可以接到controller抛出的任何未处理异常,

并不单单是HttpResponseException

异常过滤器实现了System.Web.Http.Filters.IExceptionFilter接口

代码语言:javascript
复制
 using System; 
    using System.Net; 
    using System.Net.Http; 
    using System.Web.Http.Filters; 
 
    public class NotImplExceptionFilter : ExceptionFilterAttribute  
    { 
        public override void OnException(HttpActionExecutedContext context) 
        { 
            if (context.Exception is NotImplementedException) 
            { 
                context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented); 
            } 
        } 
    } 

光创建了异常过滤器还不够

还要注册到系统中去才有效

代码语言:javascript
复制
    public class WebApiApplication : System.Web.HttpApplication
    {
        static void ConfigureApi(HttpConfiguration config)
        {
            config.Filters.Add(new HelloWebAPI.Controllers.NotImplExceptionFilter());
        } 
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            ConfigureApi(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }

我目前还不知道怎么在这里注册这个过滤器

image
image

运行的效果如下

image
image
image
image

另外

如果知识针对某个类或者某个action处理异常

也可以使用特性的写法

代码语言:javascript
复制
        [NotImplExceptionFilter]
        public IEnumerable<Product> AllProducts()
        {
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2012-07-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档