SpringBoot集成OpenApi Swagger UI 4.14异常响应不显示及200状态问题
问题分析与解决办法
核心问题
- Spring Data MongoDB的
deleteById不抛异常:这个方法不管传入的ID是否存在,都会正常执行结束,不会抛出IllegalArgumentException,导致你的异常处理器根本没机会触发,接口自然一直返回200。 - Swagger配置错误:404响应的
schema指定成了RestExceptionHandler.class,这是异常处理器类,不是实际返回的响应体结构,所以Swagger无法正确展示异常响应。 - 控制器返回
void:Spring MVC中返回void的接口默认会返回200状态码,即便后续逻辑抛了异常,也需要异常处理器返回ResponseEntity来覆盖默认状态码。
具体修复步骤
1. 修改Service层,检查ID存在性并抛异常
给deleteFromGarage方法加上存在性校验,不存在就抛出异常:
public void deleteFromGarage(String id) { if (!garageRepository.existsById(id)) { throw new IllegalArgumentException("Car with id " + id + " not found in garage"); } garageRepository.deleteById(id); }
2. 修正Swagger的@ApiResponse配置
404响应的schema要对应实际返回的内容类型(这里是异常消息字符串,或者你可以定义统一的异常DTO),而不是异常处理器类:
@Operation(summary = "Deletes a car by its id") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "A car is deleted from the Garage", content = @Content(mediaType = "application/json")), // DELETE操作通常无需返回实体,可简化 @ApiResponse(responseCode = "404", description = "A car with this id is not in our garage", content = @Content( schema = @Schema(type = "string"), // 对应返回的异常消息字符串 mediaType = "application/json"))}) @DeleteMapping(path = "/deleteCar/{carId}") public void deleteCarFromGarage(@PathVariable("carId") String id) { garageService.deleteFromGarage(id); }
3. 优化异常处理器(可选)
可以自定义统一的异常响应类,让返回结构更规范:
@Schema(description = "异常响应信息") public class ErrorResponse { @Schema(description = "错误消息") private String message; @Schema(description = "状态码") private int status; // 构造方法、getter、setter }
然后修改异常处理器:
@RestControllerAdvice public class RestExceptionHandler { @ExceptionHandler(IllegalArgumentException.class) public ResponseEntity<ErrorResponse> handleResourceNotFound(IllegalArgumentException ex) { ErrorResponse error = new ErrorResponse(); error.setMessage(ex.getMessage()); error.setStatus(HttpStatus.NOT_FOUND.value()); return new ResponseEntity<>(error, HttpStatus.NOT_FOUND); } }
同时更新Swagger的404 schema为ErrorResponse.class:
@ApiResponse(responseCode = "404", description = "A car with this id is not in our garage", content = @Content( schema = @Schema(implementation = ErrorResponse.class), mediaType = "application/json"))
4. 可选:让DELETE接口返回204 No Content
符合REST规范的做法是,删除成功后返回204状态码,修改控制器方法:
@DeleteMapping(path = "/deleteCar/{carId}") public ResponseEntity<Void> deleteCarFromGarage(@PathVariable("carId") String id) { garageService.deleteFromGarage(id); return ResponseEntity.noContent().build(); }
对应的Swagger 200响应改成204:
@ApiResponse(responseCode = "204", description = "Car deleted successfully", content = @Content)
完成以上修改后,删除不存在的ID时会触发404响应,Swagger也能正确展示异常响应结构了。
内容的提问来源于stack exchange,提问作者pussyCat
相关产品推荐
相关产品推荐

