Ser*_*nez 5 java rest json web-services spring-boot
从其他WebService返回一些错误时我遇到了一些问题.
使用标头发出请求{"Accept":"application/octet-stream"}
(ResponseEntity<InputStreamResource>如果所有进程都顺利,则服务返回文档).
当所有过程顺利进行时,文档下载得很好,但是当发生错误并且代码跳转到@ControllerAdvice并尝试返回JSON错误时.当试图返回JSON弹簧崩溃时出现问题:
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
Run Code Online (Sandbox Code Playgroud)
以下是一些代码的示例:
调节器
@RequestMapping(value = "/test", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE })
public ResponseEntity<CustomError> test() throws Exception {
throw new Exception();
}
Run Code Online (Sandbox Code Playgroud)
ControllerAdvice
@ControllerAdvice
public class ExceptionHandlerAdvice {
private static final Logger logger = LogManager.getLogger(ExceptionHandlerAdvice.class);
@ExceptionHandler({Exception.class,Throwable.class})
@ResponseBody
public ResponseEntity<CustomError> handleUnhandledException(Exception exception) {
CustomError error = new CustomError(exception.getMessage());
return new ResponseEntity<CustomError>(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Run Code Online (Sandbox Code Playgroud)
CustomError:
public class CustomError {
private String errorDescription;
public CustomError(String errorDescription) {
super();
this.errorDescription = errorDescription;
}
public String getErrorDescription() {
return errorDescription;
}
public void setErrorDescription(String errorDescription) {
this.errorDescription = errorDescription;
}
}
Run Code Online (Sandbox Code Playgroud)
我也试过在@controllerAdvice上返回新的标题
@ExceptionHandler({Exception.class,Throwable.class})
@ResponseBody
public ResponseEntity<CustomError> handleUnhandledException(Exception exception) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
CustomError error = new CustomError(exception.getMessage());
return new ResponseEntity<CustomError>(error,headers, HttpStatus.INTERNAL_SERVER_ERROR);
}
Run Code Online (Sandbox Code Playgroud)
任何想法如何使这项工作或忽略响应头上的接头?这是可能的?
提前致谢
小智 1
此异常意味着您的响应类型与请求标头不匹配。如果您期望返回 JSON/Stream,则您的请求标头应该是{"Accept":"application/octet-stream,application/json"}.
| 归档时间: |
|
| 查看次数: |
539 次 |
| 最近记录: |