Spring Boot接口抛出409异常却返回200状态码的问题解决
问题分析与解决方案
核心问题
你的代码虽然触发了InvalidDataException抛出逻辑,但Spring并未将该异常映射为HTTP 409(Conflict)响应,而是默认返回了200状态码。另外fetchSOForShipmentResolution方法在shippingOrder为null时直接返回null,后续调用shippingOrder.getBaseOrder()会触发空指针异常,同样可能被错误处理为200。
具体修复步骤
1. 给异常类绑定HTTP 409状态码
修改InvalidDataException,通过@ResponseStatus注解让Spring自动将其转换为409响应:
import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.CONFLICT) // 绑定409状态码 public class InvalidDataException extends RuntimeException { public InvalidDataException(String message) { super(message); } }
2. 修复fetchSOForShipmentResolution的空值分支
当查询不到shippingOrder时,同样抛出异常,避免后续空指针:
public ShippingOrder fetchSOForShipmentResolution(String gatewayOrderId){ ShippingOrder shippingOrder = shippingOrderService.findByGatewayOrderId(gatewayOrderId); if (shippingOrder == null) { throw new InvalidDataException("GatewayOrderId不存在"); } return shippingOrderService.verifyShipmentByGatewayOrderId(shippingOrder); }
3. 检查全局异常处理器(若存在)
如果项目中有@RestControllerAdvice标注的全局异常处理类,要确保它没有拦截InvalidDataException并强制返回200。如需统一处理,需明确返回409:
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(InvalidDataException.class) public ResponseEntity<String> handleInvalidDataException(InvalidDataException e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT); // 明确返回409 } // 其他异常处理逻辑... }
4. 验证效果
完成上述修改后,当订单状态无效或订单不存在时,Spring会直接返回HTTP 409状态码及对应异常消息,前端即可接收到预期的响应状态。
内容的提问来源于stack exchange,提问作者AasthaChaudhary
相关产品推荐
相关产品推荐

