我有一些奇怪的錯誤。Spring @ExceptionHandler返回HTTP 406
我想要做的事: 客戶詢問GET:/ invoices/invoiceNumber with header Accept:application/pdf,我想返回PDF文件。如果客戶端忘了標題,我將返回HTTP 406.
返回PDF字節的方法拋出由ExceptionHandler處理的DocumentNotFoundException,並且應該返回404,但它沒有。取而代之的是,我有406和服務器日誌:
2017-06-01 15:14:03.844 WARN 2272 --- [qtp245298614-13] o.e.jetty.server.handler.ErrorHandler : Error page loop /error
同樣的奇蹟發生在春季安全返回HTTP 401
所以我認爲,問題是,客戶接受application/pdf
,但春天的ExceptionHandler返回application/json
,所以碼頭調度覆蓋404與406 :(
我的代碼:
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Invoice not found")
@ExceptionHandler(DocumentNotFoundException.class)
public void handleException() {
//impl not needed
}
@GetMapping(value = "invoices/**", produces = MediaType.APPLICATION_PDF_VALUE)
public ResponseEntity<byte[]> getInvoicePdf(HttpServletRequest request) {
String invoiceNumber = extractInvoiceNumber(request);
final byte[] invoicePdf = invoiceService.getInvoicePdf(invoiceNumber);
return new ResponseEntity<>(invoicePdf, buildPdfFileHeader(invoiceNumber), HttpStatus.OK);
}
@GetMapping(value = "invoices/**")
public ResponseEntity getInvoiceOther() {
return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
}
有人可以幫助我理解過程rstanding?
讓你的客戶端接受'application/json' –
我想根據客戶端Accept頭返回pdf或json元數據,所以我不能改變它。 –