Spring ControllerAdvice集成Zalando Problem始终返回404求助
Spring Zalando Problem ControllerAdvice 返回404问题解决
问题描述
在Spring项目中使用Zalando Problem依赖实现ControllerAdvice,通过Postman发起HTTP请求时,断点已进入指定的if条件分支,但HTTP响应始终返回404,期望返回构建的Problem对象对应的HTTP 400 Bad Request响应。
原代码如下:
@Slf4j @ControllerAdvice public class MyExceptionHandler { @ExceptionHandler(ExceptionClassA.class) public Problem exceptionClassA(final ExceptionClassA e) { log.error(e.getMessage()); if (ObjectUtils.isNotEmpty(e.getCause()) && e.getCause() instanceof ExceptionClassB) { return Problem.builder() .withTitle("Error A") .withDetail(e.getCause().getMessage()) .withStatus(Status.BAD_REQUEST) .build(); } return Problem.builder() .withTitle("Error B") .withDetail(e.getMessage()) .withStatus(Status.INTERNAL_SERVER_ERROR) .build(); } }
解决办法
直接返回Problem对象时,Spring无法正确识别它作为响应体,也无法关联对应的HTTP状态码,导致返回404。需要用ResponseEntity<Problem>包装返回值,明确指定响应状态码和响应体。
修改后的代码:
@Slf4j @ControllerAdvice public class MyExceptionHandler { @ExceptionHandler(ExceptionClassA.class) public ResponseEntity<Problem> exceptionClassA(final ExceptionClassA e) { log.error(e.getMessage()); if (ObjectUtils.isNotEmpty(e.getCause()) && e.getCause() instanceof ExceptionClassB) { Problem problem = Problem.builder() .withTitle("Error A") .withDetail(e.getCause().getMessage()) .withStatus(Status.BAD_REQUEST) .build(); return ResponseEntity.status(problem.getStatus().getStatusCode()).body(problem); } Problem problem = Problem.builder() .withTitle("Error B") .withDetail(e.getMessage()) .withStatus(Status.INTERNAL_SERVER_ERROR) .build(); return ResponseEntity.status(problem.getStatus().getStatusCode()).body(problem); } }
额外注意事项
- 依赖检查:确保已正确引入Zalando Problem的Spring Web依赖,Maven配置示例:
<dependency> <groupId>org.zalando</groupId> <artifactId>problem-spring-web</artifactId> <version>请替换为最新稳定版本</version> </dependency>
- Jackson序列化配置:Spring Boot项目中
problem-spring-web会自动注册ProblemModule,确保Jackson能正确将Problem对象序列化为JSON响应。若需手动配置,可添加如下Bean:
@Bean public Module problemModule() { return new ProblemModule(); }
内容的提问来源于stack exchange,提问作者roadrashbuddy
相关产品推荐
相关产品推荐

