NET问答: 如何将 ASP.NET Core WebAPI 中抛出的异常封装成对象?
咨詢區(qū)
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 + 自定義錯(cuò)誤,我現(xiàn)在有兩個(gè)疑問:
直接返回錯(cuò)誤信息,不想用重量級的 throw new xxx 。
如何將錯(cuò)誤處理全局統(tǒng)一化 ?
回答區(qū)
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)} }如果你想把 錯(cuò)誤處理 應(yīng)用到全局,可以在 中間件 中實(shí)現(xiàn)異常的統(tǒng)一處理。
先定義一個(gè) 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();}點(diǎn)評區(qū)
asp.net core 的統(tǒng)一異常信息處理,這種功能真的太實(shí)用了,剛好最近做的新項(xiàng)目也搭配進(jìn)去了,不過我到?jīng)]有使用 Middleware ,而是模仿 asp.net 時(shí)代的 異常過濾器 實(shí)現(xiàn),參考代碼如下:
///?<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() 中做了一個(gè)全局注冊,參考代碼如下:
public?void?ConfigureServices(IServiceCollection?services){services.AddControllers(config?=>?{?config.Filters.Add(new?IbsExceptionFilter());?});}這種方式也是可以搞定的,實(shí)現(xiàn)方式多種多樣,以此紀(jì)念一下????????????
原文鏈接:https://stackoverflow.com/questions/43358224/how-can-i-throw-an-exception-in-an-asp-net-core-webapi-controller-that-returns-a
總結(jié)
以上是生活随笔為你收集整理的NET问答: 如何将 ASP.NET Core WebAPI 中抛出的异常封装成对象?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: EFCore3.1+编写自定义的EF.F
- 下一篇: ASP.NET Core中使用令牌桶限流