2

In a UserWithIdsRequest object

public UserWithIdsRequest{
  
    ...

    @XmlElementWrapper(name = "userIds")
    @XmlElement(name = "userId")
    private List<Long> userIds;

    ...
}

This object maps to body of get request.

There is List of userIds of type Long (cannot be changed to any other type), but some users are sendings wrong data such as name(string) , location(string) etc, when they hit the endpoint.

This ends-up giving 400 Bad Request and code never hits my requestMapping function, since I am using Java Spring.

I need to return a proper error message in scenarios where data type in wrong.

Any suggestions what can be done here?

PS: I am fairly new to Spring, do let me know if I am missing something.

aman goyal
  • 191
  • 2
  • 14
  • 1
    How to customize 400 message: https://fullstackdeveloper.guru/2020/07/08/how-to-send-a-custom-error-message-for-bad-requests-400-error-code-in-spring-boot/ (works also without "boot") – xerx593 Sep 23 '22 at 13:05
  • But be aware that "400" is broader than the described problem ... In both (Link) approaches, you have access to `exception` (message, stacktrace... ) – xerx593 Sep 23 '22 at 13:08

1 Answers1

1

You may need to receive that request body field as a List of Objects. You may also need to cast this field data while using it.

public UserWithIdsRequest{
  
    ...

    @XmlElementWrapper(name = "userIds")
    @XmlElement(name = "userId")
    private List<Object> userIds;

    ...
}
  • this is one way to do it, however application is too big to make this change. Any other suggestions? – aman goyal Sep 23 '22 at 13:03
  • 1
    @amangoyal You can also try this if possible https://stackoverflow.com/a/16655020/6784846 Like this, you can create ControllerAdvice which is the one to handle exceptions. I guess here the actual exception for 400 might be MethodArgumentNotValidException. Also here you can get the actual request parameter too – Annamalai Palanikumar Sep 23 '22 at 13:29