Feign实现自定义错误处理

问题

  • 在微服务开发当中使用了Feign进行服务之间的调用,在正常情况下是可以以响应的格式返回对象数据,但是一旦发生feign客户端的异常错误,每个下游系统的异常返回方式不同,需要编写大量的错误处理代码来适应不同的服务,而且错误处理代码混在业务代码中,违反单一职责原则和最少知识原则。面临着维护难度上升的风险。需要一个方案来规避这些后期维护成本上升的风险。

解决

  • 为了防止项目腐化,避免错误处理代码与业务代码强耦合。导致后期的维护成本的上升和陷入逻辑迷宫的风险。保证灵活性和高可维护性
  • 拆分错误处理代码和业务逻辑代码。由于使用的是 Feign和OkHttp作为客户端,而企业场景下的开发通常有统一Trac请求的需求。首先想到的是客户端的请求和响应的拦截器实现。

方案

  • 查询Feign的资料后发现Feign有 ErrorDecoder 接口。官方资料

那我们只要实现Feign的 ErrorDecoder 的接口就可以实现 http请求层面的错误处理。

官方示例:

public class StashErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        if (response.status() >= 400 && response.status() <= 499) {
            return new StashClientException(
                    response.status(),
                    response.reason()
            );
        }
        if (response.status() >= 500 && response.status() <= 599) {
            return new StashServerException(
                    response.status(),
                    response.reason()
            );
        }
        return errorStatus(methodKey, response);
    }
}

StashErrorDecoder类实现了ErrorDecoder接口。在Feign客户端发生http请求层面的错误时会调用decode方法。在decode方法中实现自定义的错误处理。

接下来就需要注册这个错误拦截器了,如果是直接手动构建FeignClient的使用方法。那需要在构建客户端时指定errorDecoder

return Feign.builder()
                .errorDecoder(new StashErrorDecoder())
                .target(StashApi.class, url);

如果是使用了spring-cloud-open-feign的使用方式,包含了启动的自动配置,所以只需要将错误处理类注册为配置类,即添加@Configuration注解即可。
具体的项目逻辑代码例子如下:

@Configuration
public class StashErrorDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String methodKey, Response response) {
        // 实现代码
         if (response.status() >= HttpStatus.BAD_REQUEST.value() && response.status() < HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                try {
                    InputStream is = response.body().asInputStream();
                    // Result是自定义的返回数据类
                    Result<?> receipt = (Result)JSON.parseObject(IOUtils.toString(is), Result.class);
                    if (receipt.getCode() == ExceptionCode.ACCOUNT_BIND.getCode()) {
                        BusinessException businessException = BusinessException.busExp(receipt.getMessage());
                        businessException.setCode(receipt.getCode());
                        return businessException;
                    }

                    return new BaseUncheckedException(receipt);
                } catch (Exception var6) {
                }
            }

            return FeignException.errorStatus(methodKey, response);
    }
}

import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;

@ApiModel(
    value = "结果集",
    description = "结果集"
)
public class Result<T> implements Serializable {
    private static final long serialVersionUID = -8621900780393672869L;
    @ApiModelProperty(
        value = "状态码",
        example = "0"
    )
    private int code = 0;
    @ApiModelProperty(
        value = "请求消息",
        example = "SUCCESS"
    )
    private String message = "SUCCESS";
    @ApiModelProperty(
        position = 2,
        value = "数据集"
    )
    private T data;

    public Result(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public Result(T data) {
        this.data = data;
    }

    public static <T> Result<T> success() {
        return new Result();
    }

    public static <T> Result<T> success(T data) {
        return new Result(data);
    }

    public static Result<String> failed(Integer code, String message) {
        return new Result(code, message);
    }

    public static Result<String> failed(IExceptionCode exceptionCode) {
        return new Result(exceptionCode.getCode(), exceptionCode.getMessage());
    }

    public static <T> Result<T> failed(BaseException e) {
        return new Result(e.getCode(), e.getMessage());
    }

    @JsonIgnore
    public boolean isSuccessful() {
        return 0 == this.code;
    }

    @JsonIgnore
    public boolean isFailed() {
        return 0 != this.code;
    }

    public int getCode() {
        return this.code;
    }

    public String getMessage() {
        return this.message;
    }

    public T getData() {
        return this.data;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setData(T data) {
        this.data = data;
    }

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof Result)) {
            return false;
        } else {
            Result<?> other = (Result)o;
            if (!other.canEqual(this)) {
                return false;
            } else if (this.getCode() != other.getCode()) {
                return false;
            } else {
                Object this$message = this.getMessage();
                Object other$message = other.getMessage();
                if (this$message == null) {
                    if (other$message != null) {
                        return false;
                    }
                } else if (!this$message.equals(other$message)) {
                    return false;
                }

                Object this$data = this.getData();
                Object other$data = other.getData();
                if (this$data == null) {
                    if (other$data != null) {
                        return false;
                    }
                } else if (!this$data.equals(other$data)) {
                    return false;
                }

                return true;
            }
        }
    }

    protected boolean canEqual(Object other) {
        return other instanceof Result;
    }

    public int hashCode() {
        int PRIME = true;
        int result = 1;
        int result = result * 59 + this.getCode();
        Object $message = this.getMessage();
        result = result * 59 + ($message == null ? 43 : $message.hashCode());
        Object $data = this.getData();
        result = result * 59 + ($data == null ? 43 : $data.hashCode());
        return result;
    }

    public String toString() {
        return "Result(code=" + this.getCode() + ", message=" + this.getMessage() + ", data=" + this.getData() + ")";
    }

    public Result() {
    }

    public Result(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }
}

  • 转载于:https://www.cnblogs.com/mufeng3421/p/11519776.html
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值