所以我有一個@RestController,我想根據前端應用程序的模式返回並驗證XML,以便在編輯器中顯示它們。我希望這些錯誤是以json格式來處理和顯示它們與js。Spring rest controller @ExceptionHandler返回xml內容和json錯誤
@RestController
public class UserController {
@RequestMapping(value = "/test",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<String> throwException(
@RequestParam(value = "flag", defaultValue = "false") Boolean flag
) throws Exception {
if (flag) {
throw new Exception();
} else {
return ResponseEntity.ok("<xml>hello</xml>");
}
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(Exception.class)
@ResponseBody
ServerError exceptionHandler(HttpServletRequest req, Exception ex) {
return new ServerError(req.getRequestURL().toString(),ex);
}
}
我想以JSON格式返回的SERVERERROR:
public class ServerError {
public final String url;
public final String error;
public ServerError(String url, Exception ex) {
this.url = url;
this.error = ex.getMessage();
}
public String getUrl() {
return url;
}
public String getError() {
return error;
}
}
所以<xml>hello</xml>
返回就好了,但是當我設置標記,以true
我得到
ERROR 2017-10-18 12:56:53,189 [http-nio-0.0.0.0-8080-exec-2] org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Failed to invoke @ExceptionHandler method: eu.openminted.registry.core.exception.ServerError eu.openminted.registry.service.UserController.malformedExeption(javax.servlet.http.HttpServletRequest,java.lang.Exception)
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
此外,將produces
設置爲XML和JSON也會得到相同的結果
@RequestMapping(value = "/test",
method = RequestMethod.GET,
produces = {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_JSON_UTF8_VALUE})
既然你解決了這個問題,你應該接受你自己的答案使人們會看到你的問題知道它已經解決了,因此可能會有所幫助。 – araknoid
@araknoid在我可以接受之前有2天的等待期。 – stevengatsios