45 lines
1.5 KiB
C#
Raw Permalink Normal View History

2025-01-13 21:06:59 +08:00
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Text;
2025-01-14 14:51:07 +08:00
using static Aliyun.OSS.Model.ListPartsResult;
2025-01-13 21:06:59 +08:00
2025-01-14 14:51:07 +08:00
namespace YD_XinWei.Commons.Exceptions.Handlers
2025-01-13 21:06:59 +08:00
{
/// <summary>
/// 自定义业务异常处理转换成为json格式
/// </summary>
public class BizExceptionHandler : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
// 1、判断异常是否BizException
if (context.Exception is BizException bizException)
{
// 1.1 将异常转换成为json结果
dynamic exceptionResult = new ExpandoObject();
2025-01-14 14:51:07 +08:00
exceptionResult.Success = false;
exceptionResult.ErrorCode = bizException.ErrorCode;
exceptionResult.ErrorMsg = bizException.ErrorMsg;
2025-01-13 21:06:59 +08:00
if (bizException.Infos != null)
{
exceptionResult.infos = bizException.Infos;
}
context.Result = new JsonResult(exceptionResult);
}
else
{
// 1.2 处理其他类型异常Exception
dynamic exceptionResult = new ExpandoObject();
2025-01-14 14:51:07 +08:00
exceptionResult.ErrorCode = -1;
exceptionResult.ErrorMsg = context.Exception.Message;
2025-01-13 21:06:59 +08:00
// 1.3 包装异常信息进行异常返回
context.Result = new JsonResult(exceptionResult);
}
}
}
}