ContentCachingRequestWrapper a request body data cache

@Component
public class RequestWrapperFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal( HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { filterChain.doFilter(new ContentCachingRequestWrapper(httpServletRequest), httpServletResponse); }}Copy the code

The @RestControllerAdvice annotation catches exceptions


@RestControllerAdvice
public class RestControllerExceptionHandler {
    private static final String TOKEN = "token"; private static final Logger LOGGER = LoggerFactory.getLogger(RestControllerExceptionHandler.class); Private static Map<String, String> getParameterMap(ServletRequest Request) {return value Map Map<String, String>returnMap = new HashMap();
        Iterator entries = request.getParameterMap().entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj) {
                value = "";
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (String string : values) {
                    value = string + ",";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        return returnMap; } @ExceptionHandler(value = Throwable.class) Response<Object> jsonErrorHandler(ServletRequest request, Throwable e) { ContentCachingRequestWrapper wrapper = (ContentCachingRequestWrapper) request; Map<String, String>returnMap = getParameterMap(request); String url = ((ContentCachingRequestWrapper) request).getRequestURI(); String token = ((ContentCachingRequestWrapper) request).getHeader(TOKEN); / / get a post request data String reqData = StringUtils. ToEncodedString (wrapper. GetContentAsByteArray (), Charset.forName(wrapper.getCharacterEncoding())); Long userId = 0L;if (null == token && StringUtils.isNotBlank(reqData)) {
            token = JSONObject.parseObject(reqData).getString(TOKEN);
            UserInfo userInfo = CommonUtils.getCurUserByToken(token);
            if(null ! = userInfo) { userId = userInfo.getId(); } } LOGGER.error("Unified catch exceptions, url: {}, token: {}, userId: {}, param: {}, body: {}",
                url,
                token,
                userId,
                returnMap,
                reqData,
                e);
        returnResponse.R500; }}Copy the code