[英]How to add error message to response body?
我有一个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状态。 我尝试了两件事:
但是该消息似乎仅显示在HTTP Status标头中。
response.getOutputStream().flush();
冲洗掉响应,但是当我尝试执行response.sendError(throwable.getRespondStatus().value());
之后,我收到一条错误消息,说我的Response is already committed
,我的身体出现了,但状态最终变为200。 关于如何设置错误消息正文的任何想法? 任何帮助,将不胜感激。 谢谢!
您不能将respons流与response.sendError(...)
结合使用。 尝试改用respons.setStatus(...)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.