tanglong 752e8450bc ss
2025-06-06 15:15:42 +08:00

45 lines
1.5 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Text;
using static Aliyun.OSS.Model.ListPartsResult;
namespace YD_XinWei.Commons.Exceptions.Handlers
{
/// <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();
exceptionResult.Success = false;
exceptionResult.ErrorCode = bizException.ErrorCode;
exceptionResult.ErrorMsg = bizException.ErrorMsg;
if (bizException.Infos != null)
{
exceptionResult.infos = bizException.Infos;
}
context.Result = new JsonResult(exceptionResult);
}
else
{
// 1.2 处理其他类型异常Exception
dynamic exceptionResult = new ExpandoObject();
exceptionResult.ErrorCode = -1;
exceptionResult.ErrorMsg = context.Exception.Message;
// 1.3 包装异常信息进行异常返回
context.Result = new JsonResult(exceptionResult);
}
}
}
}