Skip to content
Advertisement

Trying to get Spring Boot app to send an error response message when request does not have “Content-type” HTTP request header

I am still really new with Spring Boot, but I have a web application, that is setup to handle either XML requests (when the requests have a “Content-type: application/xml” header, or JSON requests (when the requests have a “Content-type: application/xml” header), and I noticed that if the “Content-type” header is either missing, or contains something other than “Content-type: application/xml” or “Content-type: application/json”, I get a “415” response error code. The logging also shows a message like:

JavaScript

I found this older SO thread:

Springboot exception handler doesn’t catch exception

and have been trying to implement the code that was posted by “Sannu” on Dec 17 ’16 at 13:55. This is the code that I built and am testing (as a test, I was trying to change the error response code to “500” and also have a error response message):

JavaScript

However, when I test, and send a request with no “Content-type:” header (using curl), I am still getting what appears to be a response with “100” response code, then a response with a “415” response code, and no response message.

FYI, here is part of the logging that is appearing:

JavaScript

Can anyone suggest why this does not seem to be able to send the error code and response message?

[FYI, I am doing this under Spring Boot 2.5.6.]

Thanks in advance!

Jim

EDIT 1: I modified the class per huy’s suggestion to this:

JavaScript

The code above causes a response with error code 415, and the text error message from the HttpMediaTypeNotSupportedException exception.

Advertisement

Answer

You don’t need to extend ExceptionHandlerException…, it’s used by default to resolve error.

You only need only ControllerAdvice and ExceptionHandler, ExceptionHandlerExceptionResolver will auto scan annotation ExceptionHandler and handle it.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement