.net core webapi 自定义异常过滤器

1.定义统一返回格式

cs 复制代码
namespace webapi;

/// <summary>
/// 统一数据响应格式
/// </summary>
public class Results<T>
{
    /// <summary>
    /// 自定义的响应码,可以和http响应码一致,也可以不一致
    /// </summary>
    public int Code { get; set; }

    /// <summary>
    /// 中文消息提示
    /// </summary>
    public string? Msg { get; set; }

    /// <summary>
    /// 是否成功
    /// </summary>
    public bool Success { get; set; }

    /// <summary>
    /// 响应的数据
    /// </summary>
    public T? Data { get; set; }

    /// <summary>
    /// 返回的Token: 如果有值,则前端需要此这个值替旧的token值
    /// </summary>
    public string? Token { get; set; }

    /// <summary>
    /// 设置数据的结果
    /// </summary>
    /// <param name="data">数据</param>
    /// <returns></returns>
    public static Results<T> DataResult(T data)
    {
        return new Results<T> { Code = 1, Data = data, Msg = "请求成功", Success = true };
    }

    /// <summary>
    /// 响应成功的结果
    /// </summary>
    /// <param name="msg"></param>
    /// <returns></returns>
    public static Results<T> SuccessResult(string msg = "操作成功")
    {
        return new Results<T> { Code = 1, Data = default, Msg = msg, Success = true };
    }

    /// <summary>
    /// 响应失败的结果
    /// </summary>
    /// <param name="msg"></param>
    /// <returns></returns>
    public static Results<T> FailResult(string msg = "请求失败")
    {
        return new Results<T> { Code = -1, Data = default, Msg = msg, Success = false };
    }

    /// <summary>
    /// 参数有误
    /// </summary>
    /// <param name="msg"></param>
    /// <returns></returns>
    public static Results<T> InValidParameter(string msg = "参数有误")
    {
        return new Results<T> { Code = -1, Data = default, Msg = msg, Success = false };
    }

    /// <summary>
    /// 获取结果
    /// </summary>
    /// <param name="code"></param>
    /// <param name="msg"></param>
    /// <param name="data"></param>
    /// <param name="success"></param>
    /// <returns></returns>
    public static Results<T> GetResult(int code = 0, string? msg = null, T? data = default, bool success = true)
    {
        return new Results<T> { Code = code, Data = data, Msg = msg, Success = success };
    }

    /// <summary>
    /// 设置token结果
    /// </summary>
    /// <param name="token"></param>
    /// <returns></returns>
    public static Results<T> TokenResult(string token)
    {
        return new Results<T> { Code = 1, Data = default, Msg = "请求成功", Success = true, Token = token };
    }
}

2.定义异常过滤器

cs 复制代码
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;

namespace webapi
{
    /// <summary>
    /// 全局异常过滤器
    /// </summary>
    public class ExceptionFilter : Attribute, IExceptionFilter
    {
        private readonly ILogger<ExceptionFilter> _logger;

        public ExceptionFilter(ILogger<ExceptionFilter> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 当发生异常的时候会执行此方法
        /// </summary>
        /// <param name="context"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void OnException(ExceptionContext context)
        {
            var values = context.RouteData.Values;
            var controller = values["controller"];
            var action = values["action"];
            _logger.LogError($"控制器:{controller},方法:{action},详细信息:\n");
            WriteDetailErrorMsg(context.Exception);
            context.Result = new JsonResult(Results<string>.FailResult(context.Exception.Message));
        }

        /// <summary>
        /// 递归获取内部异常信息
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        private void WriteDetailErrorMsg(Exception exception)
        {
            if (exception.InnerException != null)
            {
                _logger.LogError(exception.StackTrace + "\n\n");
                WriteDetailErrorMsg(exception.InnerException);
            }
            else
            {
                _logger.LogError("报错:" + exception.Message);
                _logger.LogError("堆栈跟踪:" + exception.StackTrace);
            }
        }
    }
}

3.在控制器注入自定义的异常过滤器

cs 复制代码
            builder.Services.AddControllers(opt => {
                opt.Filters.Add<ExceptionFilter>();
            });
复制代码
4.定义一个错误的api接口
cs 复制代码
        [HttpDelete]
        public ActionResult Detele()
        {
            int i = 0;//除数不能为0;
            return Content((1 / i).ToString());
        }

5.访问api接口

错误信息全记录到了,并输出到控制台,这里可以记录日志到文本文件或数据库。

相关推荐
weixin_379880929 小时前
.Net Core WebApi集成Swagger
java·服务器·.netcore
The Future is mine2 天前
.Net Core 在Linux系统下创建服务
linux·运维·.netcore
*长铗归来*3 天前
ASP.NET Core Web API 中控制器操作的返回类型及Swagger
后端·c#·asp.net·.netcore
IDOlaoluo3 天前
VS2017 安装 .NET Core 2.2 SDK 教程(包括 dotnet-sdk-2.2.108-win-x64.exe 安装步骤)
.netcore
csdn_aspnet11 天前
使用 Entity Framework Code First 方法创建 ASP.NET Core 5.0 Web API
.netcore·webapi
小先生81211 天前
.NET Core项目中 Serilog日志文件配置
c#·.netcore
爱吃香蕉的阿豪11 天前
.NET Core 中 System.Text.Json 与 Newtonsoft.Json 深度对比:用法、性能与场景选型
数据库·json·.netcore
csdn_aspnet11 天前
ASP.NET Core 10.0 的主要变化
.netcore
csdn_aspnet14 天前
在 C# .NETCore 中使用 MongoDB(第 1 部分):驱动程序基础知识和插入文档
mongodb·.netcore
csdn_aspnet14 天前
在 C# .NETCore 中使用 MongoDB(第 3 部分):跳过、排序、限制和投影
mongodb·c#·.netcore