Spring Boot项目自定义异常返回Postman时遇org.glassfish.jersey.internal.RuntimeDelegateImpl类找不到异常
Spring Boot项目自定义异常返回Postman时遇org.glassfish.jersey.internal.RuntimeDelegateImpl类找不到异常
看起来你遇到的问题根源是误用了Jersey(JAX-RS)的WebApplicationException类,而Spring Boot默认使用的是Spring MVC框架,并没有引入Jersey的相关依赖,所以运行时会找不到org.glassfish.jersey.internal.RuntimeDelegateImpl这个Jersey内部类。
下面给你两种解决方案,更推荐第一种符合Spring Boot生态的方式:
方案一:改用Spring MVC的全局异常处理体系
这是Spring Boot项目中处理自定义异常的标准做法,步骤如下:
- 修改自定义异常类,继承
RuntimeException而非WebApplicationException
public class BusinessException extends RuntimeException { private int statusCode; private String errorMessage; public BusinessException(int statusCode, String errorMessage) { super(errorMessage); this.statusCode = statusCode; this.errorMessage = errorMessage; } // 生成getter方法 public int getStatusCode() { return statusCode; } public String getErrorMessage() { return errorMessage; } }
- 创建全局异常处理器,统一处理自定义异常
用@ControllerAdvice注解实现全局异常捕获,把异常转换成你想要的JSON格式响应:
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(BusinessException.class) public ResponseEntity<ErrorResponse> handleBusinessException(BusinessException ex) { ErrorResponse errorResponse = new ErrorResponse(ex.getStatusCode(), ex.getErrorMessage()); return new ResponseEntity<>(errorResponse, HttpStatus.valueOf(ex.getStatusCode())); } // 你的ErrorResponse类保持原有结构即可 // public class ErrorResponse { // private int status; // private String message; // // 构造方法、getter和setter // } }
- 修改Service层的异常抛出代码
if (!outputDTOSet.isEmpty()) { // 正常业务逻辑 } else { throw new BusinessException(HttpStatus.NOT_FOUND.value(), "No Question Found"); }
这样处理后,当异常抛出时,全局处理器会自动捕获并返回你想要的JSON格式响应到Postman,同时不会再出现类找不到的问题。
方案二:引入Jersey依赖(不推荐)
如果你坚持要使用WebApplicationException,可以在pom.xml(Maven)或build.gradle(Gradle)中引入Jersey的starter依赖:
Maven依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jersey</artifactId> </dependency>
Gradle依赖:
implementation 'org.springframework.boot:spring-boot-starter-jersey'
不过这种方式会让Spring Boot切换到Jersey作为REST框架,可能和你原本使用的Spring MVC功能冲突,所以不推荐在Spring Boot项目中这么做。
备注:内容来源于stack exchange,提问作者DrkEthics
相关产品推荐
相关产品推荐

