简体   繁体   中英

Why sendError returns empty response body

I am trying to use sendError method from HttpServletResponse, but always get back an empty body response.

@Override
protected void doFilterInternal(@NonNull HttpServletRequest httpServletRequest, 
                                @NonNull HttpServletResponse httpServletResponse,
                                @NonNull FilterChain filterChain)
                                    throws ServletException, IOException {

        String token = jwtTokenProvider.resolveToken(httpServletRequest);
        try {
            if (token != null && jwtTokenProvider.validateToken(token)) {
                Authentication auth = jwtTokenProvider.getAuthentication(token);
                SecurityContextHolder.getContext().setAuthentication(auth);
            }
        } catch (CustomException ex) {
            SecurityContextHolder.clearContext();
            httpServletResponse.sendError(ex.getHttpStatus().value(), ex.getMessage());
            return;
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
}

Since it didn't work, I tried constructing my own response and return it to client (this is an API call).

String error = "Expired or invalid JWT token";
ApiError errorResponse = new ApiError(new Date(),500, HttpStatus.INTERNAL_SERVER_ERROR, error, ex.getLocalizedMessage(), httpServletRequest.getRequestURL().toString());
httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
httpServletResponse.getWriter().write(convertObjectToJson(errorResponse));
private String convertObjectToJson(Object object) throws JsonProcessingException {
        if (object == null) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(object);
}

This works, but I had to construct it using string and then convert it to JSON. I want to just use the sendError method. Can someone help me figure out why the response body is always empty? The status code of the empty body response (when using sendError) is 403.

I started having the same problem when I upgraded to spring boot 2.1 from 1.5.8.

Before the upgrade, the filter HeaderWriterFilter was not in the filter chain, it seems to be added by spring automatically. This filter is also calling your filter when sendError is called.

You did not mention if you are implementing Filter or extending a specific filter, but if you can extend OncePerRequestFilter it should fix the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM