如何向响应正文添加错误消息?

时间:2016-02-23 19:40:12

标签: java servlets error-handling response servlet-filters

我有一个Java Servlet类,当我的应用程序出现身份验证问题时,我尝试设置错误状态。但是,问题是,我能够设置错误状态,但无法在响应正文中设置错误消息。以下是我的尝试:

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();
}

我的throwable包含我想要显示的正确HTTP状态。我尝试了两件事:

  1. 我试着按照这个方法:public void sendError(int sc,                   java.lang.String msg)            抛出java.io.IOException
  2. 但该消息似乎只显示在HTTP状态标题中。

    1. 我尝试response.getOutputStream().flush();清除回复,但之后当我尝试执行response.sendError(throwable.getRespondStatus().value());时,我收到错误说Response is already committed,我的身体出现但状态结束了200。
    2. 有关如何设置错误消息正文的任何​​想法?任何帮助,将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:2)

您无法将责任流与response.sendError(...)结合使用。 请尝试使用respons.setStatus(...)