Home > Software design >  How to handle different data type in Request - Spring
How to handle different data type in Request - Spring

Time:09-23

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.

CodePudding user response:

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;

    ...
}

CodePudding user response:

the best way to prevent this problem is putting validation before you send data to the server use validation annotation on your field in entity ex: @NotBlank(message = "Email is mandatory")

  • Related