NetCore——自定义全局异常处理

这篇博客介绍了如何在应用程序中实现自定义异常处理,包括创建UserFriendlyException和BusinessException来封装友好的错误消息,使用AjaxResponse定义异常响应格式,通过StudentExceptionFilter自定义过滤器处理异常,并在Startup中配置自定义异常中间件。这些方法有助于提供更优雅的错误反馈和增强系统的异常处理能力。

一、UserFriendlyException自定义用户友好错误消息

  public class UserFriendlyException : BusinessException
    {
        public UserFriendlyException(
           string message,
           System.Exception innerException = null)
           //message传递给父类BusinessException
           : base(
                 message,
                 innerException)
        {
        }
    }

二、BusinessException

	//继承了系统异常
  public class BusinessException : System.Exception,
        IBusinessException
    {

        public LogLevel LogLevel { get; set; }

        public BusinessException(
            //UserFriendlyException(message)传递给Business的message
            string message = null,
            System.Exception innerException = null)
            //传递给系统异常的message(异常消息)
            : base(message, innerException)
        {
        }
    }

三、自定义异常消息格式AjaxResponse

public class AjaxResponse<TData>
    {
        /// <summary>
        /// 异常消息
        /// </summary>
        public string Message { get; set; }
        public AjaxResponse()
        {

        }

        public AjaxResponse(TData data)
        {
        }

        public AjaxResponse(string msg, bool success = false)
        {
            Message = msg;
        }

     

        public static AjaxResponse<TData> Result(bool isSuccess, int code, TData data, string message)
        {
            return new AjaxResponse<TData>
            {
                Message = message
            };
        }

四、StudentExceptionFilter自定义异常类

 public class StudentExceptionFilter:IExceptionFilter
    {
        /// <summary>
        /// 重写OnExceptionAsync方法,定义自己的处理逻辑
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public void OnException(ExceptionContext context)
        {
            //当使用UserFriendly后,自定义的异常消息,传入到了系统异常中
            var exception = context.Exception;  //获取异常消息的

            //自定义错误消息的格式
            var errorInfo = new AjaxResponse<object>("业务处理失败");
            //AjaxResponse中的message设置为,返回的异常消息的message
            errorInfo.Message = exception.Message;
            //设置返回结果为AjaxResponse格式的消息
            context.Result = new ObjectResult(errorInfo);

            //设置该异常已被处理,因为异常处理不是只有一处,设置处理,其他地方将不在处理
            context.ExceptionHandled = true; //Handled!
            //设置异常为空
            context.Exception = null; //Handled!
        }

    }

五、自定义异常注入到StartUp中

 services.AddControllersWithViews(
                options => {
                    options.Filters.Add(typeof(StudentExceptionFilter));
                        }
                )

六、自定义异常中间件

第一种当发生异常时,会进入到这里,处理异常信息,并返回

app.UseExceptionHandler(new ExceptionHandlerOptions{
    ExceptionHandler = async context=>
    {
        //包含错误的原始路径
        var exhandle = context.Features.Get<IExceptionHandlerFeature>();
        var ex = exhandle.Error;
        if(ex !=null)
        {
            context.Response.ContentType = "text/plain;charset=utf-8";
            await context.Response.WriteAsync(ex.ToString());
        }
    }
});

异常进来后,可以将错误转发到不同的异常处理,在program 中添加如下代码。

app.UseExceptionHandler(new ExceptionHandlerOptions
{
//将异常转到/error路径进行处理
    ExceptionHandlingPath = new PathString("/error")
});

/error路径错误处理逻辑

app.MapGet("/error",()=>{
    return "error1";
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有诗亦有远方

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值