I'm trying to add a custom Exception handler, which can add a more understandable response to my Spring Boot Rest API, whenever a person uses wrong Accept: Headers. Looking at my logs, the DefaultExceptionhandler resolves the following:
Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]
Writing a Custom Exception Handler, I want to return an HTTP Status BAD_REQUEST and an error message, explaining which Media Types are supported.
I tried the following Code:
@ControllerAdvice
public class CustomRestExceptionHandler {
@ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
public ResponseEntity<Error> handleException(
HttpMediaTypeNotAcceptableException e
) {
List<MediaType> supportedTypes = e.getSupportedMediaTypes();
List<String> supported = new ArrayList<>();
for (MediaType type: supportedTypes){
supported.add(type.getType()+type.getSubtype());
}
String error = "Media Type not supported. The following types are supported: " + String.join(", ", supported);
return new ResponseEntity<>(
new Error(
HttpStatus.BAD_REQUEST,
error
),
HttpStatus.BAD_REQUEST
);
}
}
@Data
public class Error {
private final HttpStatus httpStatus;
private final String message;
}
Now, whenever I use the wrong Accept:Header, I get a Warning in my logs:
97 WARN 5368 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Failure in @ExceptionHandler de.sajoconsulting.convertpdfdemo.error.CustomRestExceptionHandler#handleException(HttpMediaTypeNotAcceptableException)
And finally, the DefaultHandler resolves the Exception like normal, leading to the same HTTP Status.
I also took a look at: https://stackoverflow.com/a/74697214/20893655 which suggests it might have to do something with missing Getter and Setters, which I did provide by Lombok's @Data.