Spring clould zuul统一异常处理

  当其中的一个服务没有启动或宕机后,不能访问时,默认情况返回一个错误信息。我们统一设置一个自定义的格式,并可以发送邮件通知相关人员。代码如下:

package com.shentantech.netsec.zuul.filters;

import com.alibaba.fastjson.JSONObject;
import com.shentantech.netsec.entity.Result;
import com.shentantech.netsec.entity.StatusCode;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;


/**
 *
 */
@Component
public class ZuulFallback implements FallbackProvider {

    @Override
    public String getRoute() {
        //*代表全部服务,也可以指定具体的微服务,比如user-controller
        return "*";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return 200;
            }

            @Override
            public String getStatusText() throws IOException {
                return "OK";
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                //设置返回信息
                String result = JSONObject.toJSON(new Result(false, StatusCode.OK, "系统繁忙,请稍后重试")).toString();
                return new ByteArrayInputStream(result.getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                // headers设定,设定返回json
                HttpHeaders headers = new HttpHeaders();
                MediaType mt = new MediaType("application", "json", Charset.forName("UTF-8"));
                headers.setContentType(mt);
                return headers;
            }
        };
    }
}

  

posted @ 2019-11-26 10:35  leoBlog  阅读(259)  评论(0编辑  收藏  举报