ASP.NET Core 统一异常处理和返回
2023-02-18 15:32:22 时间
业务场景:
业务需求要求,需要对 ASP.NET Core 异常进行统一处理和返回,比如出现 500 错误和业务服务错误进行不同的处理和返回。
具体实现:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Net;
using System.Threading.Tasks;
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate next;
public ErrorHandlingMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await next(context);
}
catch (Exception ex)
{
var statusCode = context.Response.StatusCode;
if (ex is ArgumentException)
{
statusCode = 200;
}
await HandleExceptionAsync(context, statusCode, ex.Message);
}
finally
{
var statusCode = context.Response.StatusCode;
var msg = "";
if (statusCode == 401)
{
msg = "未授权";
}
else if (statusCode == 404)
{
msg = "未找到服务";
}
else if (statusCode == 502)
{
msg = "请求错误";
}
else if (statusCode != 200)
{
msg = "未知错误";
}
if (!string.IsNullOrWhiteSpace(msg))
{
await HandleExceptionAsync(context, statusCode, msg);
}
}
}
private static Task HandleExceptionAsync(HttpContext context, int statusCode, string msg)
{
var data = new { code = statusCode.ToString(), is_success = false, msg = msg };
var result = JsonConvert.SerializeObject(new { data = data });
context.Response.ContentType = "application/json;charset=utf-8";
return context.Response.WriteAsync(result);
}
}
public static class ErrorHandlingExtensions
{
public static IApplicationBuilder UseErrorHandling(this IApplicationBuilder builder)
{
return builder.UseMiddleware<ErrorHandlingMiddleware>();
}
}
Startup
添加对应配置:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseErrorHandling();
}
相关文章
- [PHP]解决 Call-time pass-by-reference has been removed
- [PHP]解决PHP Call to undefined function ldap_connect()
- [Nginx] Nginx配置PHP应用传递PATH_INFO变量
- [PHP]解决PHP Fatal error: Call to undefined function mcrypt_get_iv_size()
- [CentOS] centos下安装最新稳定版nginx
- [CentOS]查看centos的发行版本情况
- [MySQL]创建用户并指定某一数据库权限
- [PHP] 安装memcached扩展
- [http]301和302的区别
- [MySQL]简单理解并发下的CAS比较交换和ABA问题
- [前端]使用meta控制双核浏览器默认使用webkit/chrome内核
- [日常]GB2312 GBK GB18030的区别和演进过程
- [日常]中文字符串比较大小的方式
- [日常]win10解除网速限制
- [日常]解决win10没有组策略问题
- [MySQL]开启慢查询日志以及未使用索引SQL日志
- [MySQL]explain语句中type字段的具体解释
- [C语言]内存泄漏问题Out Of Memory
- [C语言]内存问题之返回局部变量地址
- [日常]windows 下 CURL SSL CA证书的位置