在 Spring Boot 中,可以使用 @ControllerAdvice
和 @ExceptionHandler
注解来捕获全局异常。@ControllerAdvice
注解允许您定义一个全局的异常处理类,而 @ExceptionHandler
注解用于处理特定类型的异常。
如下
/**
* 全局异常处理
*/
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler({BindException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Result<String> handleBindExceptionHandler(BindException e) {
log.info("参数校验异常:{}", e.getMessage());
StringBuilder errorMsg = new StringBuilder();
List<FieldError> allErrors = e.getFieldErrors();
allErrors.forEach(fieldError -> errorMsg.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage()).append("; "));
return Result.failed(errorMsg.toString());
}
@ExceptionHandler({MethodArgumentNotValidException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Result<String> handleMethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
log.info("参数校验异常:{}", e.getMessage());
StringBuilder errorMsg = new StringBuilder();
List<FieldError> allErrors = e.getBindingResult().getFieldErrors();
allErrors.forEach(fieldError -> errorMsg.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage()).append("; "));
return Result.failed(errorMsg.toString());
}
@ExceptionHandler({ValidationException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Result<String> validExceptionHandler(ValidationException e) {
log.info("参数校验异常:{}", e.getMessage());
return Result.failed(e.getMessage());
}
@ExceptionHandler({SQLException.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Result<String> sqlExceptionHandler(SQLException e) {
log.error("数据库SQL异常", e);
return Result.failed("系统异常,请稍后再试");
}
@ExceptionHandler({Exception.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Result<String> exceptionHandler(Exception e) {
log.error("系统异常:", e);
return Result.failed("系统异常,请稍后再试");
}
}