aman goyal
aman goyal

Reputation: 301

How to handle different data type in Request - Spring

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.

Upvotes: 2

Views: 624

Answers (1)

Annamalai Palanikumar
Annamalai Palanikumar

Reputation: 367

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;

    ...
}

Upvotes: 1

Related Questions