Spring Boot(15)全局异常

tech2026-02-06  1

第15篇:全局异常

流程

定义自定义异常编写异常处理器控制层抛异常

1. 定义自定义异常

@Getter public class CustomException extends RuntimeException { private String message; public CustomException(String message) { super(message); this.message = message; } }

2. 编写异常处理器

说明:rest交互,一般返回封装的response,常见为响应码、消息、数据,此处简单返回字符串

@RestControllerAdvice public class CustomExceptionHandler { @ExceptionHandler(value = CustomException.class) public String customExceptionHandler(CustomException customException) { return customException.getMessage(); } }

3. 控制层抛异常

@GetMapping("/throw/{cnt}") public String throwCustomException(@PathVariable Integer cnt) { if (cnt > 0) { throw new CustomException("Custom Exception: cnt > 0, value is: " + cnt); } return String.valueOf(cnt); }

返回:Custom Exception: cnt > 0, value is: 2

最新回复(0)