亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

統一500異常( 非拋出的異常)

標簽:
Java

%DATE% %TIME%

2021年03月11日 16:21

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

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

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:[email protected]"> 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) &amp;&amp; (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();
        }
    }
}

统一响应处理

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\":") &amp;&amp; StringUtils.contains(buffer.toString(), "\"code\":")
                &amp;&amp; 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\":") &amp;&amp; StringUtils.contains(buffer.toString(), "\"code\":")
                &amp;&amp; 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) {

        }
    }
}

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消