
@ExceptionHandler(MyCustomException.class)
public ResponseEntity<ErrorResponse> handleMyCustomException(MyCustomException ex) {
// 处理 MyCustomException 类型的异常
...
}

@ExceptionHandler(MyCustomException.class)
public ResponseEntity<ErrorResponse> handleMyCustomException(MyCustomException ex) {
// 处理 MyCustomException 类型的异常
...
}
@ExceptionHandler(AnotherCustomException.class)
public ResponseEntity<ErrorResponse> handleAnotherCustomException(AnotherCustomException ex) {
// 处理 AnotherCustomException 类型的异常
...
}
![]()

@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MyCustomException.class)
public ResponseEntity<ErrorResponse> handleMyCustomException(MyCustomException ex) {
// 创建错误响应对象
ErrorResponse errorResponse = new ErrorResponse(ex.getMessage(), HttpStatus.BAD_REQUEST.value());
// 返回响应状态码为 400 的响应
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
}

![]()
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MyCustomException.class)
public ResponseEntity<ErrorResponse> handleMyCustomException(MyCustomException ex) {
// 创建错误响应对象
ErrorResponse errorResponse = new ErrorResponse(ex.getMessage(), HttpStatus.BAD_REQUEST.value());
// 返回响应状态码为 400 的响应
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(AnotherCustomException.class)
public ResponseEntity<ErrorResponse> handleAnotherCustomException(AnotherCustomException ex) {
// 创建错误响应对象
ErrorResponse errorResponse = new ErrorResponse(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR.value());
// 返回响应状态码为 500 的响应
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
}

该博客展示了如何使用@ControllerAdvice注解实现全局异常处理。通过@ExceptionHandler分别处理MyCustomException和AnotherCustomException,返回自定义的ErrorResponse,包括错误信息和对应的HTTP状态码。全局异常处理器提高了代码的可维护性和用户体验。
1283

被折叠的 条评论
为什么被折叠?



