首页 > 其他分享 >造轮子之统一业务异常处理

造轮子之统一业务异常处理

时间:2023-10-08 11:57:22浏览次数:27  
标签:businessException Code string context 轮子 Message 异常 public 统一

异常处理也是我们必不可少的一环,借助Asp.netCore的UseExceptionHandler中间件,我们可以很轻易的配置我们的业务异常处理逻辑。

自定义业务异常类

首先我们定义一个业务异常类,继承Exception,添加一个Code状态码属性,和MessageData数组,这个数组用于Format异常信息。在实际业务场景中可以灵活扩展此类。

namespace Wheel.Core.Exceptions
{
    public class BusinessException : Exception
    {
        public string Code { get; set; }

        public string[]? MessageData { get; set; }

        public BusinessException(string code, string? message = "") : base(message)
        {
            Code = code;
        }

        public BusinessException WithMessageDataData(params string[] messageData)
        {
            MessageData = messageData;
            return this;
        }
    }
}

约定错误码

在业务开发中,我们经常需要根据错误码去判断具体的业务错误类型。所以我们需要约定一个错误码格式。
创建一个ErrorCode类。

/// <summary>
/// 错误码
/// 约定5位数字字符串
/// 4XXXX:客户端错误信息
/// 5XXXX: 服务端错误信息
/// </summary>
public class ErrorCode
{
    #region 5XXXX
    public const string InternalError = "50000";
    #endregion
    #region 4XXXX
    #endregion
}

这里我们约定一下5位数错误码,5开头则服务端的错误类型,4开头则客户端错误类型。当然,往后可以按照实际业务需求做出更多的约定或者改动。

UseExceptionHandler

接下来使用UseExceptionHandler配置我们的异常处理逻辑。
在Program中添加代码。

app.UseExceptionHandler(exceptionHandlerApp =>
{
    exceptionHandlerApp.Run(async context =>
    {
        context.Response.StatusCode = StatusCodes.Status500InternalServerError;

        // using static System.Net.Mime.MediaTypeNames;
        context.Response.ContentType = Application.Json;
        var exceptionHandlerPathFeature =
            context.Features.Get<IExceptionHandlerPathFeature>();

        if (exceptionHandlerPathFeature?.Error is BusinessException businessException)
        {
            var L = context.RequestServices.GetRequiredService<IStringLocalizerFactory>().Create(null);
            if (businessException.MessageData != null)
                await context.Response.WriteAsJsonAsync(new R { Code = businessException.Code, Message = L[businessException.Message, businessException.MessageData] });
            else
                await context.Response.WriteAsJsonAsync(new R { Code = businessException.Code, Message = L[businessException.Message] });
        }
        else
        {
            await context.Response.WriteAsJsonAsync(new R { Code = ErrorCode.InternalError, Message = exceptionHandlerPathFeature?.Error.Message });
        }
    });
});

这里判断如果是我们的BusinessException类型异常,则返回统一的Json结构,并且使用多语言处理我们的异常信息。

到这我们就轻松的完成了我们的统一业务异常处理。

欢迎进群催更。

image.png

标签:businessException,Code,string,context,轮子,Message,异常,public,统一
From: https://www.cnblogs.com/fanshaoO/p/17748530.html

相关文章

  • 造轮子之统一请求响应格式
    在上文中我们实现了统一业务异常处理,在异常响应中我们也使用了统一的响应格式返回给客户端。接下来我们就讲一下约定统一的氢气响应格式。在业务开发中,一个规范统一的请求响应格式可以提高我们的前后端开发对接效率,同时清晰的结构提高了可读性。响应基类首先定义一个最基础的只......
  • JavaSE基础05(方法,重载,调用,类和对象,构造器,封装,继承,方法重写,抽象类,接口,异常)
    面向对象以类的方式组织代码,以对象的组织封装数据;一个Java文件只能有一个public类,必须和文件名一样;java文件里也可以没有public类; 方法的定义方法的使用,修饰符返回值类型方法名(参数类型参数名){方法体return返回值};参数类型包括:基本数据类型和引用数据类......
  • Java异常(Exception)
    Java异常(Exception)Java异常是在程序执行过程中出现的错误或异常情况。异常可以分为编译时异常和运行时异常异常的分类Java中的异常分为两种类型:已检查异常(checkedexception)和运行时异常(runtimeexception)。已检查异常是在编译时被检查的异常,必须在代码中进行处理或声......
  • 前端项目异常监控-全局捕获Promise错误
    1.核心全局监听unhandledrejection,该事件为Promise被reject时但没有reject处理器时(没有被catch处理),则触发该事件。( async函数内部的异步任务一旦出现错误,那么就等同于async函数返回的Promise对象被reject。)2.编写辅助函数2.1getLastEvent获取最后一个事件letlastEv......
  • 数据库 "test1007" 的 创建 失败。其他信息: 执行 Transact-SQL 语句或批处理时发生
    问题描述在我使用sqlServer登录名和密码验证登录时,出现了创建数据库错误的信息;问题解决只需要在使用Windows身份验证进行登录后,在服务器角色里面找到dbeavor,然后将我们的登录名添加进去,保存之后,重新启动;之后再使用sqlServer验证登录连接之后,就能够建立好数据库啦!......
  • JAVA——异常
    JAVA——异常父类Exception子类RuntimeException和其他异常Exception:叫做异常,代表程序可能会出现的问题,我们通常会用Exception以及它的子类来封装程序出现的问题运行时异常:RuntimeException及其子类,编译阶段不会出现异常提醒,运行时出现的异常(如:数组越界异常)编译时异......
  • SpringMVC 异常处理
    SpringMVC异常处理异常处理类ExceptionHandlerpackagecom.tobie.globalexception;importorg.springframework.ui.ModelMap;importorg.springframework.web.bind.annotation.ControllerAdvice;importorg.springframework.web.bind.annotation.ExceptionHandler;import......
  • 202310061227-《心得:低版本mysql配置一,些轮子插件》
    1.对于mysql5.7.42,驱动(connector)选择:5.1.46。2.测试链接时:useSSL=true&enabledTLSProtocols=TLSv1.1 驱动链接字符串上要拼接上。3.驱动链接字符串:高版本mysql,意味着高版本connector,选>=8;低版本,选择5.x;               高版本mysql,com.my......
  • 自定义异常类
    继承runtimeexception可以不处理异常:packagecom.example.emos.wx.exception;importlombok.Data;@DatapublicclassEmosExceptionextendsRuntimeException{privateStringmsg;privateintcode=500;publicEmosException(Stringmsg){super......
  • asp.net mvc Core 网页错误提示:An unhandled exception occurred while processing th
    网页错误提示:Anunhandledexceptionoccurredwhileprocessingtherequest.InvalidOperationException:Theentitytype'IdentityUserLogin<string>'requiresaprimarykeytobedefined.Ifyouintendedtouseakeylessentitytype,call'Has......