统一500异常( 非抛出的异常)

2023-08-21 10:48:14 浏览数 (2)

�TE% %TIME%

2021年03月11日 16:21

这里的处理那些没有抛出的500错误

定义一个过滤器,并把级别调到最高

代码语言:javascript复制
package com.fedtech.common.filter.response;

import com.fedtech.common.util.result.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 对部分响应内容进行处理
 *
 * @author <a href = "mailto:njpkhuan@gmail.com" > huan </a >
 * @date 2021/2/24
 * @since 1.0.0
 */
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ResponseFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {

        ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) servletResponse);
        filterChain.doFilter(servletRequest, responseWrapper);
        String contentType = responseWrapper.getContentType();
        byte[] content = responseWrapper.getResponseData();
        String str = "";
        if (StringUtils.isNotBlank(contentType) && (contentType.contains(MediaType.APPLICATION_JSON_VALUE) || contentType.contains(MediaType.TEXT_HTML_VALUE))) {
            str = new String(content);
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            if (response.getStatus() != 200) {
                if (StringUtils.containsAny(str, ""status":"false"")) {
                    writeResponse(response, response.getStatus(), str);
                } else {
                    writeResponse(response, response.getStatus(), R.failedWithJsonData(str).toJson());
                }
            } else {
                if (StringUtils.containsAny(str, ""status":"true"")) {
                    writeResponse(response, response.getStatus(), str);
                } else {
                    writeResponse(response, response.getStatus(), R.successWithJsonData(str).toJson());
                }
            }
        }
    }

    private static void writeResponse(HttpServletResponse response, int status, String json) {
        try {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(status);
            response.getWriter().write(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

统一响应处理

代码语言:javascript复制
package com.fedtech.common.filter.response;

import com.fedtech.common.util.result.R;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.*;

public class ResponseWrapper extends HttpServletResponseWrapper {
    private ByteArrayOutputStream buffer = null;
    private ServletOutputStream out = null;
    private PrintWriter writer = null;

    ResponseWrapper(HttpServletResponse resp) throws IOException {
        super(resp);
        buffer = new ByteArrayOutputStream();// 真正存储数据的流
        out = new WapperedOutputStream(buffer);
        writer = new PrintWriter(new OutputStreamWriter(buffer));
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return out;
    }

    @Override
    public PrintWriter getWriter() throws UnsupportedEncodingException {
        return writer;
    }

    @Override
    public void flushBuffer() throws IOException {
        if (out != null) {
            out.flush();
        }
        if (writer != null) {
            writer.flush();
        }
    }

    @Override
    public void reset() {
        buffer.reset();
    }

    byte[] getResponseData() throws IOException {
        flushBuffer();
        if (StringUtils.contains(buffer.toString(), ""data":") && StringUtils.contains(buffer.toString(), ""code":")
                && StringUtils.contains(buffer.toString(), ""status":")) {
            return buffer.toByteArray();
        }
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        stream.write(R.successWithJsonData(buffer.toString()).toJson().getBytes());
        return stream.toByteArray();
    }

    public String getContent() throws IOException {
        flushBuffer();
        if (StringUtils.contains(buffer.toString(), ""data":") && StringUtils.contains(buffer.toString(), ""code":")
                && StringUtils.contains(buffer.toString(), ""status":")) {
            return buffer.toString();
        }
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        stream.write(R.successWithJsonData(buffer.toString()).toJson().getBytes());
        return stream.toString();
    }


    private class WapperedOutputStream extends ServletOutputStream {
        private ByteArrayOutputStream bos = null;

        WapperedOutputStream(ByteArrayOutputStream stream) throws IOException {
            bos = stream;
        }

        @Override
        public void write(int b) throws IOException {
            bos.write(b);
        }

        @Override
        public void write(byte[] b) throws IOException {
            bos.write(b, 0, b.length);
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            bos.write(b, off, len);
        }

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {

        }
    }
}

本文由博客群发一文多发等运营工具平台 OpenWrite 发布

0 人点赞