Search code examples
javajsonjakarta-eejerseyjax-rs

How abort request with JSON from ContainerRequestFilter?


I want to abort the request on an error and return JSON. But the below code simply returns a string saying "Unexpected 'U'" (That's not my message)

How do i get it to abort with a JSON response?

requestContext.abortWith(
    Response.status( Response.Status.UNAUTHORIZED ).entity(
        e.getMessage()
    ).type(
        MediaType.APPLICATION_JSON
    ).build()
);

Solution

  • Looks like e.getMessage() won't give you a valid JSON.


    Once a valid JSON can be a quoted String, you could simply add quotes to the exception message:

    String message = "\"" + e.getMessage() + "\"";
    
    requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity(message)
                                     .type(MediaType.APPLICATION_JSON).build());
    

    Alternatively you could wrap the message into a bean:

    public class ApiError {
    
        private String message;
    
        // Getters and setters
    }
    

    And then return it as the response entity:

    ApiError error = new ApiError();
    error.setMessage(e.getMessage());
    
    requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity(error)
                                     .type(MediaType.APPLICATION_JSON).build());