Return JSON on error when the header {"Accept": "application / octet-stream"} in the request

I am having trouble returning some errors from the rest of the web service.

Executing a request with the title {"Accept":"application/octet-stream"} (the service returns a ResponseEntity<InputStreamResource> document if the whole process goes well).

When the whole process goes well, the document loads normally, but when an error occurs and the code goes to @ControllerAdvice and tries to return a JSON error. This raises a problem when trying to return JSON springs:

 org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation 

Here is an example of some code:

controller

 @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; } } 

I also tried returning new headers to @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); } 

Any idea how I can make this work or ignore the Accept header in response? Is it possible?

Thank you in advance

+5
source share

Source: https://habr.com/ru/post/1271752/


All Articles