Question

For a method how can I send back a simple String in one scenario and send a object in another scenario?

For example. For signup I would like to send back a User object if the user was created successfully or a message like username already exists.

That what I have so far:

@POST
@Path("/signup")
public User signup (@Valid User user) {
  if (dao.doesUserExist(user.getName())
    //how can I return a message here?
  else 
    return createNewUser();
}
Was it helpful?

Solution 2

How about throwing:

throw new WebApplicationException(409);

This indicates that there's a conflict. It's also more useful to the client than returning an error string.

OTHER TIPS

Does this help?

@POST
@Path("/path")
public Response signup (@Valid User user)
{

  if (dao.doesUserExist(user.getName())
    //return a message here
    Response.status(Status.CONFLICT).type(MediaType.TEXT_PLAIN).entity("user already exists, but due to OWASP (https://www.owasp.org/index.php/Authentication_Cheat_Sheet) -> An application should respond with a generic error message regardless of whether the user ID or password was incorrect. It should also give no indication to the status of an existing account. ").build();
  else 
    return createNewUser();

}

You can use Response to return a simple message to client, in your return you can change User to Response and return in response body your creted user or message

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top