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

1.定义统一返回格式

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.定义异常过滤器

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.在控制器注入自定义的异常过滤器


            builder.Services.AddControllers(opt => {
   
                opt.Filters.Add<ExceptionFilter>();
            });

4.定义一个错误的api接口

        [HttpDelete]
        public ActionResult Detele()
        {
   
            int i = 0;//除数不能为0;
            return Content((1 / i).ToString());
        }

5.访问api接口
在这里插入图片描述
错误信息全记录到了,并输出到控制台,这里可以记录日志到文本文件或数据库。

相关推荐

  1. qt定义事件过滤器

    2023-12-28 05:20:06       30 阅读
  2. 认识异常定义异常

    2023-12-28 05:20:06       27 阅读
  3. 定义异常

    2023-12-28 05:20:06       24 阅读
  4. Spring Cloud Gateway定义过滤器

    2023-12-28 05:20:06       47 阅读
  5. 3.3 Gateway之定义过滤器

    2023-12-28 05:20:06       26 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-28 05:20:06       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-28 05:20:06       106 阅读
  3. 在Django里面运行非项目文件

    2023-12-28 05:20:06       87 阅读
  4. Python语言-面向对象

    2023-12-28 05:20:06       96 阅读

热门阅读

  1. linux统计文件数量命令

    2023-12-28 05:20:06       59 阅读
  2. 记录 | python with用法及原理

    2023-12-28 05:20:06       60 阅读
  3. cfa一级考生复习经验分享系列(十二)

    2023-12-28 05:20:06       56 阅读
  4. 面试经典150题(50-53)

    2023-12-28 05:20:06       62 阅读
  5. Day01-Ajax

    2023-12-28 05:20:06       48 阅读
  6. MySQL5.7服务器系统变量(二)

    2023-12-28 05:20:06       50 阅读
  7. 深入了解 Python 的 import 语句

    2023-12-28 05:20:06       50 阅读
  8. Python批处理excel文件多个sheet汇总脚本

    2023-12-28 05:20:06       55 阅读
  9. 网页设计——中国梦

    2023-12-28 05:20:06       56 阅读
  10. C++中的左值,右值和移动语义详解

    2023-12-28 05:20:06       66 阅读
  11. Linux ftp

    Linux ftp

    2023-12-28 05:20:06      50 阅读
  12. 2024上岸计划

    2023-12-28 05:20:06       56 阅读