欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

controller层统一捕获异常(重点:解决HttpServletRequest inputStream只能读取一次的问题)...

程序员文章站 2022-03-01 15:49:08
...

ContentCachingRequestWrapper缓存一份请求的body数据

@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);
    }
}
复制代码

@RestControllerAdvice注解捕获异常


@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) {
        // 返回值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;
        //获取get请求的数据
        Map<String, String> returnMap = getParameterMap(request);
        String url = ((ContentCachingRequestWrapper) request).getRequestURI();
        String token = ((ContentCachingRequestWrapper) request).getHeader(TOKEN);
        //获取post请求的数据
        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(
                "统一捕获异常,url:{},token:{},userId:{},param:{},body:{}",
                url,
                token,
                userId,
                returnMap,
                reqData,
                e);
        return Response.R500;
    }
}
复制代码