Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 445
Ryan Avatar asked Apr 02 '19 04:04

Ryan


1 Answers

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.

like image 122
Garage Coder Avatar answered Sep 29 '22 03:09

Garage Coder