Write a unified exception handling class under Spring

Unified exception handling

  • @ControllerAdvice
  • 1), write exception handling class, use @ControllerAdvice.
  • 2) Use @ExceptionHandler to annotate the exceptions that can be handled.
  • The first step: extract an exception handling class ExceptionControllerAdvice:
/**
*集中处理异常
*/
//注明此异常处理类需要处理哪个包出现的异常
@RestControllerAdvice(basePackages = "com.controller")
/*@org.springframework.web.bind.annotation.ControllerAdvice*/
public class ControllerAdvice {
    
    
	//感知异常ExceptionHandler,告诉SpringMVC此方法可以处理哪些异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
    
    
        log.error("数据校验出现问题{},异常类型{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError)->{
    
    
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",errorMap);
    }
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable t){
    
    
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}

Note: The first method to pass the parameter MethodArgumentNotValidException is an exception reported by my project, and the second method handles all exceptions.
Insert picture description here

BizCodeEnume class (specify error code and error message):

public enum BizCodeEnume {
    
    
    UNKNOW_EXCEPTION(10000,"系统未知异常"),
    VAILD_EXCEPTION(10001,"参数格式校验失败");
    private int code;
    private String msg;
    BizCodeEnume(int code,String msg){
    
    
        this.code = code;
        this.msg = msg;
    }

    public int getCode() {
    
    
        return code;
    }

    public String getMsg() {
    
    
        return msg;
    }
}

Guess you like

Origin blog.csdn.net/lq1759336950/article/details/113776820