2017-06-01 93 views
2

我有一些奇怪的错误。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?

+0

让你的客户端接受'application/json' –

+0

我想根据客户端Accept头返回pdf或json元数据,所以我不能改变它。 –

回答

0

问题是,Spring试图将错误响应转换为application/pdf,但未能找到合适的支持转换为PDF的HttpMessageConverter

的最简单的解决方案是手动创建错误响应:

@ExceptionHandler(DocumentNotFoundException.class) 
public ResponseEntity<?> handleException(DocumentNotFoundException e) { 

    return ResponseEntity 
     .status(HttpStatus.NOT_FOUND) 
     .contentType(MediaType.APPLICATION_JSON_UTF8) 
     .body("{\"error\": \"Invoice not found\"}"); 
} 

这绕过消息转换并导致HTTP 404响应代码。

+0

是啊,这件事情我想和它的作品,但我想避免它,becouse: *我想返回错误cosistent的方式与别人端点 *在这种情况下,我应该为所有可能的例外创建自定义异常处理程序,为了返回前。 400,401,404等 –

+0

也许你应该尝试[Spring Web MVC的问题](https://github.com/zalando/problem-spring-web)这是一个库,它可以很容易地生成'application /来自Spring应用程序的问题+ json'响应。但是,如果我的答案解决了您的具体问题,请作为回答upvote。 –

相关问题