日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

NET问答: 如何将 ASP.NET Core WebAPI 中抛出的异常封装成对象?

發布時間:2023/12/4 asp.net 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 NET问答: 如何将 ASP.NET Core WebAPI 中抛出的异常封装成对象? 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

咨詢區

rianjs

在 ASP.NET Core WebAPI 中,我的 Controller 代碼如下:

[Route("create-license/{licenseKey}")] public?async?Task<LicenseDetails>?CreateLicenseAsync(string?licenseKey,?CreateLicenseRequest?license) {try{//?...?controller-y?stuffreturn?await?_service.DoSomethingAsync(license).ConfigureAwait(false);}catch?(Exception?e){_logger.Error(e);const?string?msg?=?"Unable?to?PUT?license?creation?request";throw?new?HttpResponseException(HttpStatusCode.InternalServerError,?msg);} }

上面的這段代碼如果拋異常了,將返回 http 500 + 自定義錯誤,我現在有兩個疑問:

  • 直接返回錯誤信息,不想用重量級的 throw new xxx 。

  • 如何將錯誤處理全局統一化 ?

回答區

peco

如果不想用 throw new 的話,可以把 CreateLicenseAsync() 方法稍微改造一下。

  • 返回值改成 IActionResult

  • throw new 改成 StatusCode

參考代碼如下:

[Route("create-license/{licenseKey}")] public?async?Task<IActionResult>?CreateLicenseAsync(string?licenseKey,?CreateLicenseRequest?license) {try{//?...?controller-y?stuffreturn?Ok(await?_service.DoSomethingAsync(license).ConfigureAwait(false));}catch?(Exception?e){_logger.Error(e);const?string?msg?=?"Unable?to?PUT?license?creation?request";return?StatusCode((int)HttpStatusCode.InternalServerError,?msg)} }

如果你想把 錯誤處理 應用到全局,可以在 中間件 中實現異常的統一處理。

先定義一個 ExceptionMiddleware 中間件。

public?class?ExceptionMiddleware {private?readonly?RequestDelegate?_next;public?ExceptionMiddleware(RequestDelegate?next){_next?=?next;}public?async?Task?Invoke(HttpContext?context){try{await?_next(context);}catch?(Exception?ex){context.Response.ContentType?=?"text/plain";context.Response.StatusCode?=?(int)HttpStatusCode.InternalServerError;await?context.Response.WriteAsync(ex.Message);????}} }

接下來將其注入到 request pipeline 中即可。

public?void?Configure(IApplicationBuilder?app,?IWebHostEnvironment?env,?ILoggerFactory?loggerFactory){app.UseMiddleware<ExceptionMiddleware>();app.UseMvc();}

點評區

asp.net core 的統一異常信息處理,這種功能真的太實用了,剛好最近做的新項目也搭配進去了,不過我到沒有使用 Middleware ,而是模仿 asp.net 時代的 異常過濾器 實現,參考代碼如下:

///?<summary>///?全局異常處理///?</summary>public?class?IbsExceptionFilter?:?ExceptionFilterAttribute{public?override?Task?OnExceptionAsync(ExceptionContext?context){context.ExceptionHandled?=?true;HttpResponse?response?=?context.HttpContext.Response;response.StatusCode?=?200;response.ContentType?=?"application/json";var?message?=?context.Exception.Message;context.Result?=?new?JsonResult(ApiResponse.Err(message));return?Task.CompletedTask;}}

然后我在 ConfigureServices() 中做了一個全局注冊,參考代碼如下:

public?void?ConfigureServices(IServiceCollection?services){services.AddControllers(config?=>?{?config.Filters.Add(new?IbsExceptionFilter());?});}

這種方式也是可以搞定的,實現方式多種多樣,以此紀念一下????????????

原文鏈接:https://stackoverflow.com/questions/43358224/how-can-i-throw-an-exception-in-an-asp-net-core-webapi-controller-that-returns-a

總結

以上是生活随笔為你收集整理的NET问答: 如何将 ASP.NET Core WebAPI 中抛出的异常封装成对象?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。