Spring Boot 全局异常处理机制
在 Spring Boot 应用中,统一异常处理是提升系统健壮性和用户体验的关键环节。通过 @ControllerAdvice 配合 @ExceptionHandler,我们可以集中捕获并处理控制器层抛出的异常,避免将原始堆栈信息直接暴露给前端。
核心实现
定义一个全局异常处理类时,需添加 @ControllerAdvice 注解标识为通知类,并在具体处理方法上使用 @ExceptionHandler 指定要处理的异常类型。若接口返回数据格式需要 JSON,务必确保类或方法上存在 @ResponseBody(或类级别使用 @RestController)。
异常处理器示例
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.model.Result;
@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {
@ExceptionHandler
public Result handlerException(Exception e) {
log.error("发生未知异常", e);
return Result.fail("内部错误");
}
@ExceptionHandler(NullPointerException.class)
public Result handlerException(NullPointerException e) {
log.error("发生空指针异常", e);
return Result.fail("参数为空");
}
@ExceptionHandler(ArithmeticException.class)
public Result handlerException(ArithmeticException e) {
log.error("发生算术异常", e);
return Result.fail("计算错误");
}
}


