user1871869
user1871869

Reputation: 3367

How to add error message to response body?

I have a Java Servlet class where I try to set the error status when there is an authentication issue in my application. However, the issue is, I am able to set the error status but am not able to set an error message in the body of the response. Below is my attempt:

AuthorizationFilter.java

public class AuthorizationFilter implements Filter {
    @Autowired
    private ExceptionHandler exceptionHandler;

    @Override
    public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) servletRequest;
        final HttpServletResponse response = (HttpServletResponse) servletResponse;

        UserSession userSession = null;
        try {
             userSession = authProvider.authenticate(request, response);
        } catch(RestUsageException throwable) {
            exceptionHandler.handle(throwable.getExceptionCode(), throwable.getMessage(), throwable, response);
            response.sendError(throwable.getRespondStatus().value());
        //  response.sendError(throwable.getRespondStatus().value(), "Message");
            return;
        }
    ...more code here
    }

ExceptionHandler.java

@Override
public void handle(String exceptionCode, String message, Throwable throwable, final ServletResponse response) throws IOException {

    String uuid = UUID.randomUUID().toString();
    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    String json = "{  \n" +
                "   \"errorCode\":\""+exceptionCode+"\",\n" +
                "   \"errorMessage\":\""+throwable.getMessage()+"\",\n" +
                "   \"success\":\"false\",\n" +
                "   \"errorId\":\""+uuid+"\"\n" +
                "}";
    response.getOutputStream().println(json);
  //  response.getOutputStream().flush();
}

My throwable contains the correct HTTP status that I want to display. I tried two things:

  1. I tried to do follow this method: public void sendError(int sc, java.lang.String msg) throws java.io.IOException

But the message seems to only be displayed in the HTTP Status header.

  1. I tried to response.getOutputStream().flush(); to flush out the response but then when I try to perform response.sendError(throwable.getRespondStatus().value()); afterwards, I get an error saying my Response is already committed, and my body shows up but the status ends up being 200.

Any ideas on how to set the error message body? Any help would be appreciated. Thanks!

Upvotes: 1

Views: 7773

Answers (1)

gustf
gustf

Reputation: 2017

You cant use the respons streams in combination with response.sendError(...). Try to use respons.setStatus(...) instead.

Upvotes: 2

Related Questions