我在REST Web服务中处理了自定义错误。我有返回XML / JSON作为响应的方法。在SpringBoot版本2.0.9上,一切正常。但是,在迁移到最新版本(2.2.4)之后,我的错误处理测试失败了:
Content type expected:<application/xml> but was:<application/json>
Expected :application/xml
Actual :application/json
研究后,我发现它与将Spring升级到5.1版有关。文件:
错误响应的内容协商@RequestMapping的产生条件不再影响错误响应的内容类型。
如何从最新的Spring早期版本中重现行为?我只想返回内容类型,以获取produces条件中指定的错误。
其余方法:
@PostMapping(path = "/{scriptName}", produces = { MediaType.APPLICATION_XML_VALUE }) public ResponseEntity<Object> xmlMethod(@RequestParam("payload") String payload, @PathVariable("scriptName") String scriptName) { Object result = service.call(payload, scriptName); return ResponseEntity.ok(new JsonBuilder(result).getContent()); } @PostMapping(path = "/{scriptName}", produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity<Object> jsonMethod(@RequestParam("payload") String payload, @PathVariable("scriptName") String scriptName) { Object result = service.call(payload, scriptName); return ResponseEntity.ok(new JsonBuilder(result).getContent()); }
CustomRestExceptionHandler:
@ControllerAdvice public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<Object> handleResourceNotFoundException(ResourceNotFoundException ex, WebRequest request) { HTTPErrorDTO httpError = new HTTPErrorDTO(HttpStatus.NOT_FOUND, ex.getLocalizedMessage()); return new ResponseEntity<>(httpError, new HttpHeaders(), httpError.getStatus()); } .... // handlers for other exceptions }
错误DTO:
@XmlRootElement(name = "Exception") @XmlAccessorType(XmlAccessType.FIELD) public class HTTPErrorDTO { private HttpStatus status; private String message; private List<String> errors; }
相关主题:Spring mvc - Configuring Error handling for XML and JSON Response
我在REST Web服务中处理了自定义错误。我有返回XML / JSON作为响应的方法。在SpringBoot版本2.0.9上一切正常。但是在迁移到最新版本(2.2.4)之后,我的错误...
这可能会帮助-:使用Spring Boot实施内容协商[https://www.javainuse.com/spring/spring-boot-content-negotiation][1]