In my spring boot application, I have a controller for post request which produces and consumes JSON request and I have defined @ExceptionHandler for this controller with HttpMediaTypeNotAcceptableException for catching HttpMediaTypeNotAcceptableException(406 status code) exceptions.
Now whenever I call the post request with a wrong header of ACCEPT such as application/pdf, the defined exception does not get called.
I don't want to define ControllerAdvice since I would like to throw a specific error for this controller.
code:
@RestController
@RequestMapping("/school")
public class SchoolCotroller {
@Autowired
private SchoolService schoolService;
@PostMapping(produces = "Application/Json", consumes = "Application/Json")
@ResponseStatus(HttpStatus.CREATED)
public School postData(@Valid @RequestBody School school) {
return schoolService.save(school);
}
@ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
String handleMediaTypeNotAcceptable(
final HttpMediaTypeNotAcceptableException exception,
final NativeWebRequest request) {
return "acceptable MIME type:" + MediaType.APPLICATION_JSON_VALUE;
}
}
curl:
curl --location --request POST 'http://localhost:8080/school' \
--header 'Accept: application/pdf' \
--header 'Content-Type: application/json' \
--data-raw '{
"studentName":"mayank",
"course":1,
"teacher":"e",
"id":1
}'
So whenever I call this Curl request I get default bad request response with console log as "DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]" but it does not call the ExceptionHandler method.
Why is it not calling the required ExceptionHandler method?