グローバル例外インターセプト ハンドラーを定義する

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 を通じて、例外処理の結果が直接返されます。

おすすめ

転載: blog.csdn.net/wang121213145/article/details/131706314
おすすめ