Spring自定义异常
# 自定义异常
创建自定义异常类;
继承自RuntimeException或其子类;
public class CustomException extends RuntimeException { public CustomException() { super(); } public CustomException(String message) { super(message); } public CustomException(String message, Throwable cause) { super(message, cause); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14Spring控制器处理异常;
@ControllerAdvice表示全局异常处理器;
@ExceptionHandler处理自定义异常;
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(CustomException.class) public ResponseEntity<String> handleCustomException(CustomException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } }
1
2
3
4
5
6
7
8