当处理Spring Boot应用程序中的全局异常时,可以使用@ControllerAdvice和@ExceptionHandler注解来实现一个优雅的统一异常处理。
步骤1:创建Spring Boot项目
在IntelliJ IDEA中创建一个新的Spring Boot项目,并添加所需的依赖。
步骤2:定义自定义异常类
在项目的src/main/java目录下,创建一个自定义异常类,用于表示应用程序中可能发生的异常。
public class CustomException extends RuntimeException {
private String errorCode;
private String errorMessage;
public CustomException(String errorCode, String errorMessage) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
// getter and setter methods
}
步骤3:创建统一异常处理类
在项目的src/main/java目录下,创建一个统一异常处理类,使用@ControllerAdvice和@ExceptionHandler注解来捕获和处理全局异常。
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(CustomException.class)
public ResponseEntity<ErrorResponse> handleCustomException(CustomException ex) {
ErrorResponse errorResponse = new ErrorResponse(ex.getErrorCode(), ex.getErrorMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGenericException(Exception ex) {
ErrorResponse errorResponse = new ErrorResponse("500", "Internal Server Error");
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
步骤4:创建错误响应类
在项目的src/main/java目录下,创建一个错误响应类,用于封装错误信息。
public class ErrorResponse {
private String errorCode;
private String errorMessage;
public ErrorResponse(String errorCode, String errorMessage) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
// getter and setter methods
}
步骤5:创建示例控制器
在项目的src/main/java目录下,创建一个示例控制器类,用于触发自定义异常。
@RestController
public class ExampleController {
@GetMapping("/example")
public void example() {
throw new CustomException("400", "Bad Request");
}
}
步骤6:运行应用程序
在IntelliJ IDEA中,运行Spring Boot应用程序。
步骤7:测试异常处理
使用任何HTTP客户端(例如Postman)访问http://localhost:8080/example路径,应该会触发CustomException,并返回错误响应。