[Solved] springsecurity custom exceptions: Error: Parse Error: Response overflow

preface

In the process of writing the project, using springsecurity for permission management and customizing the token filter to be added before the authentication filter, there was a problem where the exception handling mechanism of springsecurity would be called when the token expired, instead of using my global exception handling

Solution:

Custom filter

package com.fruiter.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Handling exceptions thrown by Controller will be handled by this filter
 */
public class ControllerExceptionFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            filterChain.doFilter(request, response);
        } catch (ExpiredJwtException e) {
            e.printStackTrace();

            response.setStatus(401);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print("token过期");
        }
    }

    public String convertObjectToJson(Object object) throws JsonProcessingException {
        if (object == null) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(object);
    }
}

Join for management

//WebAsyncManagerIntegrationFilter is the first exception handling filter
http.addFilterBefore(new ControllerExceptionFilter(), WebAsyncManagerIntegrationFilter.class);

be careful

Here, set the status code for response, that is, response.setStatus(401);
you can’t set an excessively large number such as 10010, otherwise an error will report error: parse error: response overflow

Modify it to 401.

Read More: