Springboot2.x uniformly intercepts the specified Exception

Springboot2.x uniformly intercepts the specified Exception

Intercept Exception ControllerAdvice returns 400
Intercept AuthorizationException returns 401

@ControllerAdvice
public class ExceptionControllerAdvice {
    
    

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseEntity<ResponseResultVO> bindExceptionHandler(BindException exception) {
    
    
        exception.printStackTrace();
        BindingResult result = exception.getBindingResult();
        String errorMsg = null;
        if (result.hasErrors()) {
    
    
            Set<FieldError> fieldErrors = new HashSet<>(result.getFieldErrors());
            errorMsg = fieldErrors.iterator().next().getDefaultMessage();
        }
        return ResponseEntity.badRequest().body(ResponseResultVO.builder().code(ErrorCodeConstant.VALID_ERROR).msg(errorMsg).build());
    }

    @ExceptionHandler(value = AuthorizationException.class)
    @ResponseBody
    public ResponseEntity<ResponseResultVO> authorExceptionHandler(AuthorizationException e) {
    
    
        return ResponseEntity.status(401).body(ResponseResultVO.builder().code(ErrorCodeConstant.VALID_ERROR).msg(e.getMessage()).build());
    }
}

Guess you like

Origin blog.csdn.net/weixin_38045214/article/details/115299929