说明 @ControllerAdvice / @ExceptionHandler 与统一响应。
用 @RestControllerAdvice(= @ControllerAdvice + @ResponseBody)配合 @ExceptionHandler 统一拦截异常:
@RestControllerAdvice
public class GlobalEx {
@ExceptionHandler(BizException.class)
public Result<Void> handle(BizException e) {
return Result.fail(e.getCode(), e.getMessage());
}
@ExceptionHandler(Exception.class)
public Result<Void> handleAll(Exception e) {
log.error("err", e);
return Result.fail(500, "系统异常");
}
}
要点:就近精确异常优先;返回统一 Result 结构;配合 HTTP 状态码(@ResponseStatus);校验异常用 MethodArgumentNotValidException。
题目与答案就在本页;收藏、批注和错题重练在应用内