我从其他WebService返回一些错误时遇到了一些问题。
使用标头{"Accept":"application/octet-stream"}
发出请求
(如果所有过程都顺利,该服务将返回文档ResponseEntity<InputStreamResource>
)。
当所有过程顺利进行时,文档下载正常,但是当发生错误并且代码跳转到@ControllerAdvice
并尝试返回JSON错误时。当试图返回JSON弹簧崩溃时,问题出现了:
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
以下是一些代码示例:
控制器
@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();
}
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);
}
}
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;
}
}
我也尝试在@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);
}
任何想法如何使这项工作或在响应时忽略Accept标头? 有可能吗?
提前致谢