Spring @ExceptionHandler and HttpMediaTypeNotAcceptableException
The problem lies in the incompatibility of the requested content type and the object being returned. See my response on how to configure the ContentNegotiationConfigurer
so that Spring determines the requested content type according to your needs (looking at the path extension, URL parameter or Accept
header).
Depending on how the requested content type is determined, you have following options when an image is requested by the client:
- if the requested content type is determined by the
Accept
header, and if the client can/wants to handle a JSON response instead of the image data, then the client should send the request withAccept: image/*, application/json
. That way Spring knows that it can safely return either the image byte data or the error JSON message. - in any other case your best solution is to just return a HTTP error code, without any error message. You can do that in a couple of ways in your controller:
Set the error code on the response directly
public byte[] getImage(HttpServletResponse resp) {
try {
// return your image
} catch (Exception e) {
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
Use ResponseEntity
public ResponseEntity<?> getImage(HttpServletResponse resp) {
try {
byte[] img = // your image
return ReponseEntity.ok(img);
} catch (Exception e) {
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Use a separate @ExceptionHandler
method in that controller, which will override the default Spring exception handling. That assumes you have either a dedicated exception type for image requests or a separate controller just for serving the images. Otherwise, the exception handler will handle exceptions from other endpoints in that controller, too.
What does your ExceptionInfo
class look like? I run into quite similar issue after defining a few exception handlers in @ControllerAdvice
annotated class. When exception happened it was caught, although the response was not return and org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
was thrown.
I figured out that the problem was caused by the fact, that I missed to add getter methods to my ErrorResponse
class. After adding getter methods (this class was immutable, so there were no setter methods) everything worked like a charm.