[英]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. 我有一个Java Servlet类,当我的应用程序中存在身份验证问题时,我尝试在其中设置错误状态。 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 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 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. 我的
throwable
包含我要显示的正确的HTTP状态。 I tried two things: 我尝试了两件事:
But the message seems to only be displayed in the HTTP Status header. 但是该消息似乎仅显示在HTTP Status标头中。
response.getOutputStream().flush();
response.getOutputStream().flush();
to flush out the response but then when I try to perform response.sendError(throwable.getRespondStatus().value());
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. Response is already committed
,我的身体出现了,但状态最终变为200。 Any ideas on how to set the error message body? 关于如何设置错误消息正文的任何想法? Any help would be appreciated.
任何帮助,将不胜感激。 Thanks!
谢谢!
You cant use the respons streams in combination with response.sendError(...)
. 您不能将respons流与
response.sendError(...)
结合使用。 Try to use respons.setStatus(...)
instead. 尝试改用
respons.setStatus(...)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.