定义全局异常拦截处理器

在Java中,我们通过注解@ControllerAdvice@ExceptionHandler来进行全局的异常处理
直接看我定义的异常配置类:

package com.youming.client.commons.exception;

import com.youming.client.commons.response.ResponseCode;
import com.youming.client.commons.response.ResponseResult;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Xii
 * @Description 全局异常拦截处理器
 * @Date 15:07 2023/6/25
 * @Param
 * @return 
 **/
@ControllerAdvice
@ResponseBody
@Log4j2
public class GlobalExceptionHandler {
    @ExceptionHandler({ BusinessException.class, Exception.class })
    public ResponseResult handlerException(HttpServletRequest request, Exception ex) {
        Map<String, Object> error = new HashMap<>(2);
        // 业务异常
        if (ex instanceof BusinessException) {
            error.put("code", ((BusinessException) ex).getCode());
            error.put("message", ex.getMessage());
            printLog(ex, error, "[全局业务异常]\r\n业务编码:{}\r\n异常记录:{}\r\n异常位置:{}");
        }
        // 统一处理Json 参数验证
//        else if (ex instanceof MethodArgumentNotValidException) {
//            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) ex;
//            BindingResult bindingResult = methodArgumentNotValidException.getBindingResult();
//            String msg = bindingResult.getFieldErrors().stream().map(FieldError::getDefaultMessage).distinct()
//                    .collect(Collectors.joining(","));
//            error.put("code", HttpStatus.BAD_REQUEST.value());
//            error.put("message", msg);
//            printLog(ex, error, "[系统异常--json]\r\n业务编码:{}\r\n异常记录:{}\r\n异常位置:{}");
//        }
//
//        // 统一处理表单绑定验证
//        else if (ex instanceof BindException) {
//            BindException bindException = (BindException) ex;
//            BindingResult bindingResult = bindException.getBindingResult();
//            String msg = bindingResult.getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage)
//                    .distinct().collect(Collectors.joining(","));
//            error.put("code", HttpStatus.BAD_REQUEST.value());
//            error.put("message", msg);
//            printLog(ex, error, "[系统异常--表单处理]\r\n业务编码:{}\r\n异常记录:{}\r\n异常位置:{}");
//        }
        else {
            error.put("code", ResponseCode.UNKNOWN.code());
            error.put("message", ResponseCode.SYSTEM_UNKNOWN.message());
            printLog(ex, error, "[系统异常]\r\n业务编码:{}\r\n异常记录:{}\r\n异常位置:{}");
        }

        return new ResponseResult(ResponseCode.BUS_FAILED,error.get("message"));
    }

    private void printLog(Exception ex, Map<String, Object> error, String s) {
        StringBuilder sbException = new StringBuilder();
        for (StackTraceElement ele : ex.getStackTrace()) {
            sbException.append(MessageFormat.format("\tat {0}.{1}({2}:{3})\n", ele.getClassName(), ele.getMethodName(),
                    ele.getFileName(), ele.getLineNumber()));
            ;
        }
        // System.out.println(sbException);
        log.warn(s, error.get("code"), error.get("message"), sbException);
    }
}

通过@ResponseBody,将异常处理的结果直接返回。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

杵意

谢谢金主打赏呀!!

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

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

打赏作者

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

抵扣说明:

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

余额充值