在Spring Boot中,您可以通过全局异常处理器来统一处理应用程序中的异常,并返回JSON格式的错误响应。下面是一个示例:
- 创建一个自定义异常类来表示应用程序的特定异常:
public class CustomException extends RuntimeException {
private String errorCode;
private String errorMessage;
// 构造函数和getter/setter方法
}
- 创建一个全局异常处理器类,并使用
@ControllerAdvice
和@ExceptionHandler
注解:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(CustomException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorResponse handleCustomException(CustomException ex) {
return new ErrorResponse(ex.getErrorCode(), ex.getErrorMessage());
}
// 其他异常处理方法
}
在上述示例中,handleCustomException()
方法使用@ExceptionHandler
注解来处理CustomException
类型的异常。它返回一个ErrorResponse
对象作为JSON格式的响应。
- 创建一个
ErrorResponse
类来表示错误响应的结构:
public class ErrorResponse {
private String errorCode;
private String errorMessage;
// 构造函数和getter/setter方法
}
- 在
ErrorResponse
类中,您可以根据需要添加其他字段,如错误代码、时间戳等。
通过以上步骤,您可以定义自己的异常类、全局异常处理器和错误响应类,在应用程序发生异常时返回JSON格式的错误响应。请根据实际需求进行适当的调整和扩展。