Spring Cloud Feign + Hystrix custom exception handler

Open Hystrix

After the spring-cloud-dependencies Dalston version, the default Feign support for Hystrix is ​​off by default, need to manually open.

feign.hystrix.enabled=true

Fallback

fallback fallback method is used when Hystrix command fails, the processing logic used to implement the services degraded. In HystrixCommand service degradation can be achieved by overriding logic getFallback () method, Hystrix will () error occurs during execution in the run, time out, the thread pool refusal, when a short-circuit fuse and so on, do getFallback () method within the logic.

Typically, when the main method of HystrixCommand ( run()an exception is thrown), the trigger will getFallback (). With one exception - HystrixBadRequestException. When thrown HystrixBadRequestException, regardless of whether the current Command defined getFallback (), will not trigger, but an exception is thrown upward.

There are some anomalies want to throw up, instead of firing Fallback strategy, they can be packaged to achieve if the business HystrixBadRequestExceptionin.

getFallback () execution time not under the control of HystrixCommand timeout.

Encapsulation of the exception Feign

By implementing FallbackFactory, you can createget to the service exception thrown method. Note, however, where the exception is Feignencapsulated over abnormality, the original can not be seen directly in an exception thrown exception information.

1. Custom error decoder, do not enter the fuse, to preserve the original error message, the method to the upper thrown.

package test.config;

import com.alibaba.fastjson.JSONObject;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

public class NotBreakerConfiguration {
    @Bean
    public ErrorDecoder errorDecoder() {
        return new SpecialErrorDecoder();
    }
    /**
     * 自定义错误
     */
    public class SpecialErrorDecoder implements ErrorDecoder {
        private Logger logger = LoggerFactory.getLogger(getClass());
        @Override
        public Exception decode(String methodKey, Response response) {
            Exception exception = null;
            try {
                String json = Util.toString(response.body().asReader());
                exception = new RuntimeException(json);
                JsonResult result = JSONObject.parseObject(json, JsonResult.class);
                // 业务异常包装成 HystrixBadRequestException,不进入熔断逻辑
                if (!result.isSuccess()) {
                    exception = new HystrixBadRequestException(result.getMessage());
                }
            } catch (IOException ex) {
                logger.error(ex.getMessage(), ex);
            }
            return exception;
        }
    }
}

2. Specify the error decoder is FeignClient, choose one:

1) is specified in the client

@FeignClient(name = "service-name", 
fallbackFactory = TestServiceFallback.class, 
configuration = {NotBreakerConfiguration.class})
public interface TestService {
    // 省略
}

2) specified in the configuration file

feign:
  client:
    config:
      servive-name:
        error-decoder: NotBreakerConfiguration

3. Über

package course.aftersale.service;

import com.netflix.hystrix.exception.HystrixBadRequestException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TestServiceApi {

    public void withdraw() {
        try {
            // 省略feign client方法调用
        } catch (HystrixBadRequestException e) {
            // 原始错误信息
            log.info(e.getMessage());
        } catch (Exception e) {
            log.error("error", e);
        }
    }
}

Reference:
https://blog.csdn.net/lvyuan1234/article/details/77155919
https://juejin.im/post/5bae37ca5188255c652d4c6a
https://my.oschina.net/xiaominmin/blog/2986631/print

Guess you like

Origin www.cnblogs.com/ylty/p/12004276.html