Spring Cloud Feign异常处理机制

在Spring Cloud 微服务中不可避免的使用Feign来远程调用其他服务接口,一般情况下,会在报文格式中冗余一个响应码和响应信息的字段,例如:

{
  "msg": "产品不存在",
  "code": 40005,
  "data": null
}

在调用Feign接口时,我们都希望直接返回的就是想要的结果,如果每个接口的返回数据都要像上边一样,就需要对返回的数据进行处理,是非常繁琐的,而且会造成代码的冗余,但是当被调用服务抛出业务异常时,FeignClient抛出的异常是被封装过的,无法获得有用的信息,所以就需要设计一套机制来处理返回数据。

下面是我的解决方案:

1.统一封装异常码

/**
 * @author:JZ
 * @date:2020/3/15
 */
public enum ResultCode {

    SUCCESS(00000, "成功"),
    FAIL(99999, "失败"),
    SYSTEM_EXCEPTION(10000, "系统异常")

    ;

    private Integer code;

    private String message;

    ResultCode(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

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

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

}

2.统一异常

这里只是父类,可以延伸出子类

import com.jz.shop.commons.enums.ResultCode;
import lombok.Data;

/**
 * @author:JZ
 * @date:2020/4/19
 */
@Data
public class BaseException extends RuntimeException {

    private Integer code;

    private String msg;

    public BaseException() {
        super();
    }

    public BaseException(ResultCode resultCode) {
        super(resultCode.getMessage());
        this.code = resultCode.getCode();
        this.msg = resultCode.getMessage();
    }

    public BaseException(Integer code, String message) {
        super(message);
        this.code = code;
        this.msg = message;
    }

}

3.全局异常处理器

由全局异常处理器处理所有异常,并对返回结果进行处理

package com.jz.shop.commons.handler.exception;

import com.jz.shop.commons.enums.ResultCode;
import com.jz.shop.commons.execptions.BaseException;
import com.jz.shop.commons.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author:JZ
 * @date:2020/5/16
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 系统异常处理器
     * @param throwable
     * @param request
     * @return
     */
    @ExceptionHandler(Throwable.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)   // 指定http状态码,如果不指定为非2xx,feign不会抛出异常
    public Result systemExceptionHandler(Throwable throwable, HttpServletRequest request) {
        log.error("URL:{} ,系统异常", request.getRequestURI(), throwable);
        return Result.fail(Result.success(ResultCode.SYSTEM_EXCEPTION));
    }

    /**
     * 自定义异常处理器
     */
    @ExceptionHandler(BaseException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)   // 指定http状态码,如果不指定为非2xx,feign不会抛出异常
    public Result baseExceptionHandler(BaseException baseException, HttpServletRequest request) {
        log.warn("URL:{} ,业务异常", request.getRequestURI());
        return Result.fail(baseException.getCode(), baseException.getMsg());
    }

}

4.自定义处理Feign调用异常

实现 Feign 的 ErrorDecoder 接口,抛出自定义异常。

import com.alibaba.fastjson.JSONObject;
import com.jz.shop.commons.execptions.BaseException;
import com.jz.shop.commons.execptions.system.SystemException;
import com.jz.shop.commons.model.Result;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;

/**
 * feign异常处理
 * @author:JZ
 * @date:2020/5/16
 */
@Slf4j
public class FeignErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String s, Response response) {
        BaseException baseException = null;
        try {
            String errorContent = Util.toString(response.body().asReader());
            Result result = JSONObject.parseObject(errorContent, Result.class);
            baseException = new BaseException(result.getCode(), result.getMsg());
        } catch (Exception e) {
            log.error("处理FeignClient 异常错误");
            e.printStackTrace();
            return SystemException.DEFAULT_SYSTEM_EXCEPTION;
        }
        return baseException;
    }

}

5.总结

经过上述处理即使连续调用了多个Feign接口,异常信息也会被逐级传递,同时不用影响 Hmily

你可能感兴趣的:(spring,cloud)