javajsonmavenjerseygrizzly

How to return a string in response that have @Produces(MediaType.APPLICATION_JSON)?


@GET
@Path("/paises/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response findCountryList(@PathParam("id")int id){
    try{
    ArrayList<Country> lista = new ArrayList<>();
    for(int i=0; i<10 ;i++){
        Country c = new Country();
        c.setId(i);
        c.setName("country"+i);
        c.setCode("countryIsoCode"+i);
        c.setRegion("region"+i);
        lista.add(c);
        }
    
    Country co = lista.stream().filter(x -> x.getId()==id).findAny().get();
    if(id > lista.size()-1) throw new Exception("That id is not correct");
    return Response.ok(co).build();
    }catch(Exception e){
        
        return Response.status(404).entity(e.getMessage()).build();
        }
    }

I want to return a json when I don't have an Exception but when i have it I need to return a string with the exception message but this drop error of json parse.


Solution

  • A single quoted string is a valid JSON. So you could use:

    return Response.status(404).entity("\"" + e.getMessage() + "\"").build();
    

    However I advise you to return a JSON object instead. It gives you the flexibility to return extra metadata about the error.

    You could use a Map<String, Object>:

    Map<String, Object> errorDetails = new HashMap<>();
    errorDetails.put("message", e.getMessage());
    return Response.status(404).entity(errorDetails).build();
    

    Or create a class for the error details:

    public class ErrorDetails {
    
        private String message;
    
        ...
    }
    
    ErrorDetails errorDetails = new ErrorDetails;
    errorDetails.setMessage(e.getMessage());
    return Response.status(404).entity(errorDetails).build();
    

    For reporting problems in an HTTP API, have a look at the RFC 7807.