我有一個休息API在春天生成和下載PDF文件。控制器definitation如下 -春天 - 無法發送API返回錯誤消息ByteArrayResource
@RequestMapping(
value = "/foo/bar/pdf",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
@ResponseBody
@Nullable
public ByteArrayResource downloadPdf(@RequestParam int userId) {
byte[] result = null;
ByteArrayResource byteArrayResource = null;
result = service.generatePdf(userId);
if (result != null) {
byteArrayResource = new ByteArrayResource(result);
}
return byteArrayResource;
}
我用傑克遜JSON處理JSON,並有一個異常處理程序ControllerAdvice。問題是,當這個API產生一個異常,我返回一個自定義的異常類(包含消息和一個額外的字段)。
正如我已經指定produces = MediaType.APPLICATION_OCTET_STREAM_VALUE
這個自定義類也試圖被轉換爲一個八位字節流由春,它失敗併產生HttpMediaTypeNotAcceptableException: Could not find acceptable representation
。
我試過this#1的問題,特別是解決this answer,但它仍然失敗。此解決方案以及其他更改建議從@RequestMapping
中刪除produces
部分,但是當我調試到AbstractMessageConverterMethodProcessor.getProducibleMediaTypes
時,它僅檢測到application/json作爲可用響應介質類型。
TL;博士 我怎麼能有這樣的API返回成功的文件和正確的錯誤返回自定義異常類的JSON表示。