首页 > 编程语言 >C# .NET6 WebAPI 全局异常过滤器

C# .NET6 WebAPI 全局异常过滤器

时间:2024-04-02 10:22:05浏览次数:33  
标签:WebAPI Code const string 自定义 C# int NET6 public

自定义返回级别

namespace Demo
{
    /// <summary>
    /// 自定义返回级别
    /// </summary>
    public enum ResultLevel : int
    {
        /// <summary>
        /// 正确
        /// </summary>
        OK = 0,
        /// <summary>
        /// 警告
        /// </summary>
        Warning = 1,
        /// <summary>
        /// 异常
        /// </summary>
        Error = 2
    }
}
View Code

自定义返回代码

namespace Demo
{
    /// <summary>
    /// 自定义返回代码
    /// </summary>
    public enum ResultCode : int
    {
        /// <summary>
        /// 正确
        /// </summary>
        OK = 0,
        /// <summary>
        /// 用户名或密码错误
        /// </summary>
        LoginFailed = 1,
        /// <summary>
        /// 身份认证失败
        /// </summary>
        IdentityAuthFailed = 2,
        /// <summary>
        /// 数据模型已存在
        /// </summary>
        ModelIsExist = 101,
        /// <summary>
        /// 数据模型不存在
        /// </summary>
        ModelNoExist = 102,
        /// <summary>
        /// 数据模型错误
        /// </summary>
        ModelError = 103,
        /// <summary>
        /// 文件校验失败
        /// </summary>
        FileError = 104,
        /// <summary>
        /// MQTT回执超时
        /// </summary>
        MqttRecriptTimeout = 105,
        /// <summary>
        /// MQTT回执结果失败
        /// </summary>
        MqttRecriptResultFail = 106,
        /// <summary>
        /// HTTP请求失败
        /// </summary>
        HttpRequestFail = 107,
        /// <summary>
        /// 请求内容类型错误
        /// </summary>
        ContentTypeError = 996,
        /// <summary>
        /// 用户信息异常
        /// </summary>
        UserInfoError = 997,
        /// <summary>
        /// 系统异常
        /// </summary>
        LogicError = 998,
        /// <summary>
        /// 系统异常
        /// </summary>
        OtherError = 999
    }
}
View Code

自定义返回信息

namespace Demo
{
    /// <summary>
    /// 自定义返回信息
    /// </summary>
    public class ResultMsg
    {
#pragma warning disable CS1591 // 缺少对公共可见类型或成员的 XML 注释
        public const string OK = "ok";
        public const string LoginFailed = "用户名或密码错误";
        public const string IdentityAuthFailed = "身份认证失败";
        public const string ModelIsExist = "数据模型已存在";
        public const string ModelNoExist = "数据模型不存在";
        public const string ModelError = "数据模型错误";
        public const string FileError = "文件校验失败";
        public const string MqttRecriptTimeout = "等待MQTT回执超时";
        public const string ContentTypeError = "请求内容类型错误";
        public const string UserInfoError = "用户信息异常";
        public const string LogicError = "业务逻辑异常";
        public const string OtherError = "系统内部异常";
        public const string HttpRequestFail = "HTTP请求失败:{0}";
#pragma warning restore CS1591 // 缺少对公共可见类型或成员的 XML 注释
    }
}
View Code

自定义返回结构

namespace Demo
{
    /// <summary>
    /// 自定义返回结构
    /// </summary>
    public class CustomResult<T>
    {
        /// <summary>
        /// 返回码
        /// </summary>
        public string? Code { get; set; }
        /// <summary>
        /// 返回信息
        /// </summary>
        public string? Msg { get; set; } = ResultMsg.OK;
        /// <summary>
        /// 返回数据
        /// </summary>
        public T? Data { get; set; }
        /// <summary>
        /// 构造函数
        /// </summary>
        public CustomResult()
        {
            Code = ((int)ResultLevel.OK).ToString() + ((int)ResultCode.OK).ToString("D3");
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="t"></param>
        public CustomResult(T? t)
        {
            if (t is CustomException cex)
            {
                Code = ((int)cex.Level).ToString() + ((int)cex.Code).ToString("D3");
                Msg = cex.Message;
            }
            else if (t is Exception)
            {
                Code = ((int)ResultLevel.Error).ToString() + ((int)ResultCode.OtherError).ToString("D3");
                Msg = ResultMsg.OtherError;
            }
            else
            {
                Code = ((int)ResultLevel.OK).ToString() + ((int)ResultCode.OK).ToString("D3");
                Data = t;
            }
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="level"></param>
        /// <param name="code"></param>
        /// <param name="t"></param>
        public CustomResult(ResultLevel level, ResultCode code, T t)
        {
            Code = ((int)level).ToString() + ((int)code).ToString("D3");
            Data = t;
        }
    }
}
View Code

自定义异常类

namespace Demo
{
    /// <summary>
    /// 自定义异常类
    /// </summary>
    [Serializable]
    public class CustomException : Exception
    {
        /// <summary>
        /// 错误级别
        /// </summary>
        public ResultLevel Level { get; set; } = ResultLevel.Error;
        /// <summary>
        /// 错误码
        /// </summary>
        public ResultCode Code { get; set; } = ResultCode.OtherError;
        /// <summary>
        /// 构造函数
        /// </summary>
        public CustomException()
        {
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="message"></param>
        public CustomException(string? message) : base(message)
        {
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="errLevel"></param>
        /// <param name="errCode"></param>
        /// <param name="message"></param>
        public CustomException(ResultLevel errLevel, ResultCode errCode, string? message) : base(message)
        {
            Level = errLevel;
            Code = errCode;
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="errLevel"></param>
        /// <param name="errCode"></param>
        public CustomException(ResultLevel errLevel, ResultCode errCode) : base()
        {
            Level = errLevel;
            Code = errCode;
        }
    }
}
View Code

自定义异常过滤器(控制器全局异常过滤器)

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Demo
{
    /// <summary>
    /// 自定义异常过滤器(控制器异常)
    /// </summary>
    public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger _logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        public CustomExceptionFilterAttribute(ILogger<CustomExceptionFilterAttribute> logger)
        {
            _logger = logger;
        }
        /// <summary>
        /// 发生异常事件
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(ExceptionContext context)
        {
            // 自定义异常
            if (context.Exception is CustomException ex)
            {
                _logger.LogError(ex, ResultMsg.LogicError);
                var result = new CustomResult<CustomException>(ex);
                context.Result = new BadRequestObjectResult(result);
            }
            // 系统异常
            else
            {
                _logger.LogError(context.Exception, ResultMsg.OtherError);
                var result = new CustomResult<Exception>(context.Exception);
                context.Result = new ObjectResult(result) { StatusCode = StatusCodes.Status500InternalServerError };
            }
            // 标记异常已处理
            context.ExceptionHandled = true;
        }
        /// <summary>
        /// 发生异常事件
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task OnExceptionAsync(ExceptionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            OnException(context);
            return Task.CompletedTask;
        }
    }
}
View Code

使用方法

// 添加控制器
builder.Services.AddControllers(options =>
{
    // 自定义异常过滤器(仅对控制器级别的错误进行处理)
    options.Filters.Add(typeof(CustomExceptionFilterAttribute));
})
View Code

 

翻译

搜索

复制

标签:WebAPI,Code,const,string,自定义,C#,int,NET6,public
From: https://www.cnblogs.com/smartnn/p/18110017

相关文章

  • C# 生成JWT
    usingMicrosoft.IdentityModel.Tokens;usingSystem.IdentityModel.Tokens.Jwt;usingSystem.Security.Claims;usingSystem.Text;namespaceDemo{///<summary>///Token处理类///</summary>publicclassToken{///<......
  • 英语背单词 专四词汇 2024年04月 ChatGPT
    2024-04-03  2024-04-02  2024-04-01IndexWordPronunciationPartsofSpeechExplanationTranslationinChinese1insulationɪnsəˈleɪʃənnounMaterialorsubstanceusedtopreventheat,electricity,orsoundfrompassing绝缘;隔热材料2......
  • QT开发:报错:QAxBase: Error calling IDispatch member Open: Exception thrown by serv
    在Qt中打开excel出现下面的错误提示:QAxBase:ErrorcallingIDispatchmemberOpen:Exceptionthrownbyserver怎么解决?错误提示通常意味着在尝试使用Qt的ActiveX模块(QAxBase)打开Excel文件时发生了异常。这可能是由于多种原因引起的,包括文件损坏、权限问题、Excel安装问题或者Q......
  • docker-compose 部署OWASP Juice Shop + CTFd
    项目介绍1.OWASPJuiceShop原文OWASPJuiceShopisprobablythemostmodernandsophisticatedinsecurewebapplication!Itcanbeusedinsecuritytrainings,awarenessdemos,CTFsandasaguineapigforsecuritytools!JuiceShopencompassesvulnerabili......
  • How to fix: “inotify cannot be used, reverting to polling: Too many open files
    Youareherebecauseyouhadencounteredtheerrorinthetitle.InthisarticleIwillexplaintheerrorandstepsnecessarytoreproduceandfixit.Themostrelevantdocumentationforinotifyisthe inotifymanpage, thatyoucanalsoreadlocallywith......
  • Quill文档(四):使用Parchment克隆Medium
    为了提供一致的编辑体验,您需要一致的数据和可预测的行为。不幸的是,DOM缺乏这两个特性。现代编辑器的解决方案是维护自己的文档模型来表示它们的内容。对于Quill来说,Parchment就是这样的解决方案。它在自己的代码库中组织,并拥有自己的API层。通过Parchment,您可以定制Quill识别......
  • CDR2024序列号keygen注册机最新免费网盘下载
    CorelDRAW2024是一款智能高效的平面设计软件,广泛应用于排版印刷、矢量图形编辑及网页设计等领域。它集矢量绘图、文本编辑、图像处理等多种功能于一身,可以满足各种设计需求。来自UC网盘分享文件:CDR2019-2024新旧软件安装包网盘绿色下载地址链接:手机打开微信扫一扫获取网盘......
  • BetterZip2024Mac上一款功能强大的Mac平台解压压缩软件
    一、软件概述BetterZip是一款Mac平台上的压缩解压缩工具,它为用户提供了一个方便的方式来处理各种压缩文件,包括但不限于ZIP、TAR、GZIP等格式。除了基本的压缩解压缩功能外,BetterZip还具备文件预览、文件加密、分卷压缩等高级功能,使得用户能够更加灵活高效地管理自己的压缩文件......
  • 【Python BUG】ImportError: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `CX
    报错ImportError:/usr/lib/x86_64-linux-gnu/libstdc++.so.6:version`CXXABI_1.3.9‘notfound背景开发的一个python预测程序(算法分析+应用服务),在原本的linux服务器下配置了开发环境,打包后在另一台凝思服务器解压,发现报错。应该是linux系统之间存在差异,动态库缺失......
  • C++ | filesystem file not found
    1.filesystem使用过程中遇到的错误如果你用的GCC版本<GCC8.0,则直接#include<filesystem>会报错,说找不到文件Nosuchfileordirectory对于这种情况,可以如下操作。如果是GCC8.0+和C++17以上,则只需要#include<filesystem>①改include路径#include<experimental/filesystem......