feign.codec.ErrorDecoder Java Examples

The following examples show how to use feign.codec.ErrorDecoder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AsynchronousMethodHandler.java    From feign-vertx with Apache License 2.0 6 votes vote down vote up
private AsynchronousMethodHandler(
    final Target<?> target,
    final VertxHttpClient client,
    final Retryer retryer,
    final List<RequestInterceptor> requestInterceptors,
    final Logger logger,
    final Logger.Level logLevel,
    final MethodMetadata metadata,
    final RequestTemplate.Factory buildTemplateFromArgs,
    final Decoder decoder,
    final ErrorDecoder errorDecoder,
    final boolean decode404) {
  this.target = target;
  this.client = client;
  this.retryer = retryer;
  this.requestInterceptors = requestInterceptors;
  this.logger = logger;
  this.logLevel = logLevel;
  this.metadata = metadata;
  this.buildTemplateFromArgs = buildTemplateFromArgs;
  this.errorDecoder = errorDecoder;
  this.decoder = decoder;
  this.decode404 = decode404;
}
 
Example #2
Source File: FeignTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void throwsRetryableExceptionIfNoUnderlyingCause() throws Exception {
  server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 1"));
  server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 2"));

  String message = "play it again sam!";
  thrown.expect(RetryableException.class);
  thrown.expectMessage(message);

  TestInterface api = Feign.builder()
      .exceptionPropagationPolicy(UNWRAP)
      .retryer(new Retryer.Default(1, 1, 2))
      .errorDecoder(new ErrorDecoder() {
        @Override
        public Exception decode(String methodKey, Response response) {
          return new RetryableException(response.status(), message, HttpMethod.POST, null,
              response.request());
        }
      }).target(TestInterface.class, "http://localhost:" + server.getPort());

  api.post();
}
 
Example #3
Source File: FeignTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void throwsOriginalExceptionAfterFailedRetries() throws Exception {
  server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 1"));
  server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 2"));

  final String message = "the innerest";
  thrown.expect(TestInterfaceException.class);
  thrown.expectMessage(message);

  TestInterface api = Feign.builder()
      .exceptionPropagationPolicy(UNWRAP)
      .retryer(new Retryer.Default(1, 1, 2))
      .errorDecoder(new ErrorDecoder() {
        @Override
        public Exception decode(String methodKey, Response response) {
          return new RetryableException(response.status(), "play it again sam!", HttpMethod.POST,
              new TestInterfaceException(message), null, response.request());
        }
      }).target(TestInterface.class, "http://localhost:" + server.getPort());

  api.post();
}
 
Example #4
Source File: FeignTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void ensureRetryerClonesItself() throws Exception {
  server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 1"));
  server.enqueue(new MockResponse().setResponseCode(200).setBody("foo 2"));
  server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 3"));
  server.enqueue(new MockResponse().setResponseCode(200).setBody("foo 4"));

  MockRetryer retryer = new MockRetryer();

  TestInterface api = Feign.builder()
      .retryer(retryer)
      .errorDecoder(new ErrorDecoder() {
        @Override
        public Exception decode(String methodKey, Response response) {
          return new RetryableException(response.status(), "play it again sam!", HttpMethod.POST,
              null, response.request());
        }
      }).target(TestInterface.class, "http://localhost:" + server.getPort());

  api.post();
  api.post(); // if retryer instance was reused, this statement will throw an exception
  assertEquals(4, server.getRequestCount());
}
 
Example #5
Source File: ReactiveFeignIntegrationTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"ThrowableNotThrown"})
@Test
public void testErrorDecoder() {
  this.webServer.enqueue(new MockResponse().setBody("Bad Request").setResponseCode(400));

  ErrorDecoder errorDecoder = mock(ErrorDecoder.class);
  given(errorDecoder.decode(anyString(), any(Response.class)))
      .willReturn(new IllegalStateException("bad request"));

  TestReactiveXService service = RxJavaFeign.builder()
      .errorDecoder(errorDecoder)
      .target(TestReactiveXService.class, this.getServerUrl());
  StepVerifier.create(service.search(new SearchQuery()))
      .expectErrorSatisfies(ex -> assertThat(ex)
          .isInstanceOf(IllegalStateException.class)
          .hasMessage("bad request"))
      .verify();
  verify(errorDecoder, times(1)).decode(anyString(), any(Response.class));
}
 
Example #6
Source File: TransactionFeignErrorDecoder.java    From ByteJTA with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void invokeAfterPropertiesSet() throws Exception {
	feign.codec.ErrorDecoder errorDecoder = null;

	String[] beanNameArray = this.applicationContext.getBeanNamesForType(feign.codec.ErrorDecoder.class);
	for (int i = 0; beanNameArray != null && i < beanNameArray.length; i++) {
		String beanName = beanNameArray[i];
		Object beanInst = this.applicationContext.getBean(beanName);
		if (TransactionFeignErrorDecoder.class.isInstance(beanInst)) {
			continue;
		} else if (errorDecoder != null) {
			throw new RuntimeException("There are more than one feign.codec.ErrorDecoder exists!");
		} else {
			errorDecoder = (feign.codec.ErrorDecoder) beanInst;
		}
	}

	if (errorDecoder == null) {
		errorDecoder = new ErrorDecoder.Default();
	} // end-if (errorDecoder == null)

	this.delegate = errorDecoder;
}
 
Example #7
Source File: Issue362Tests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void should_successfully_work_with_custom_error_decoder_when_sending_failing_request() {
	String securedURl = "http://localhost:9998/sleuth/test-not-ok";

	try {
		this.template.getForEntity(securedURl, String.class);
		fail("should propagate an exception");
	}
	catch (Exception e) {
	}

	then(this.feignComponentAsserter.executedComponents)
			.containsEntry(ErrorDecoder.class, true)
			.containsEntry(Client.class, true);
	// retries
	then(this.spans).hasSize(5);
	then(this.spans.spans().stream().map(span -> span.tags().get("http.status_code"))
			.collect(Collectors.toList())).containsOnly("409");
}
 
Example #8
Source File: CompensableFeignErrorDecoder.java    From ByteTCC with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void invokeAfterPropertiesSet() throws Exception {
	feign.codec.ErrorDecoder errorDecoder = null;

	String[] beanNameArray = this.applicationContext.getBeanNamesForType(feign.codec.ErrorDecoder.class);
	for (int i = 0; beanNameArray != null && i < beanNameArray.length; i++) {
		String beanName = beanNameArray[i];
		Object beanInst = this.applicationContext.getBean(beanName);
		if (CompensableFeignErrorDecoder.class.isInstance(beanInst)) {
			continue;
		} else if (errorDecoder != null) {
			throw new RuntimeException("There are more than one feign.codec.ErrorDecoder exists!");
		} else {
			errorDecoder = (feign.codec.ErrorDecoder) beanInst;
		}
	}

	if (errorDecoder == null) {
		errorDecoder = new ErrorDecoder.Default();
	} // end-if (errorDecoder == null)

	this.delegate = errorDecoder;
}
 
Example #9
Source File: AsynchronousMethodHandler.java    From feign-vertx with Apache License 2.0 6 votes vote down vote up
MethodHandler create(
    final Target<?> target,
    final MethodMetadata metadata,
    final RequestTemplate.Factory buildTemplateFromArgs,
    final Decoder decoder,
    final ErrorDecoder errorDecoder) {
  return new AsynchronousMethodHandler(
      target,
      client,
      retryer,
      requestInterceptors,
      logger,
      logLevel,
      metadata,
      buildTemplateFromArgs,
      decoder,
      errorDecoder,
      decode404);
}
 
Example #10
Source File: FeignHelper.java    From eventapis with Apache License 2.0 6 votes vote down vote up
@Bean
public ErrorDecoder errorDecoder() {
    return (methodKey, response) -> {
        String errorDesc = null;
        try {
            errorDesc = IOUtils.toString(response.body().asInputStream(), "utf-8");
            return objectMapper.readValue(errorDesc, Exception.class);
        } catch (Exception e) {
            log.error("Feign error decoder exception : ", e);
            if (errorDesc != null) {
                return new Exception("Unclassified Error " + errorDesc);
            } else {
                return new Exception("Unclassified Error Unexpected Error");
            }
        }
    };
}
 
Example #11
Source File: AnnotationErrorDecoderNoAnnotationTest.java    From feign-annotation-error-decoder with Apache License 2.0 6 votes vote down vote up
@Test
public void delegatesToDefaultErrorDecoder() throws Exception {

  ErrorDecoder defaultErrorDecoder = new ErrorDecoder() {
    @Override
    public Exception decode(String methodKey, Response response) {
      return new DefaultErrorDecoderException();
    }
  };

  AnnotationErrorDecoder decoder =
      AnnotationErrorDecoder.builderFor(TestClientInterfaceWithNoAnnotations.class)
          .withDefaultDecoder(defaultErrorDecoder)
          .build();

  assertThat(decoder.decode(feignConfigKey("method1Test"), testResponse(502)).getClass())
      .isEqualTo(DefaultErrorDecoderException.class);
}
 
Example #12
Source File: ReactiveStatusHandlers.java    From feign-reactive with Apache License 2.0 6 votes vote down vote up
public static ReactiveStatusHandler defaultFeign(ErrorDecoder errorDecoder) {
  return new ReactiveStatusHandler() {

    @Override
    public boolean shouldHandle(int status) {
      return familyOf(status).isError();
    }

    @Override
    public Mono<? extends Throwable> decode(String methodTag, ReactiveHttpResponse response) {
      return response.bodyData().map(bodyData -> errorDecoder.decode(methodTag,
          Response.builder().status(response.status())
              .reason(HttpStatus.getStatusText(response.status()))
              .headers(response.headers().entrySet()
                  .stream()
                  .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)))
              .body(bodyData).build()));
    }
  };
}
 
Example #13
Source File: ReactiveStatusHandlers.java    From feign-reactive with Apache License 2.0 6 votes vote down vote up
public static ReactiveStatusHandler defaultFeign(ErrorDecoder errorDecoder) {
  return new ReactiveStatusHandler() {

    @Override
    public boolean shouldHandle(int status) {
      return familyOf(status).isError();
    }

    @Override
    public Mono<? extends Throwable> decode(String methodTag, ReactiveHttpResponse response) {
      return response.bodyData()
              .defaultIfEmpty(new byte[0])
              .map(bodyData -> errorDecoder.decode(methodTag,
                      Response.builder().status(response.status())
                              .reason(HttpStatus.getStatusText(response.status()))
                              .headers(response.headers().entrySet()
                                      .stream()
                                      .collect(Collectors.toMap(Map.Entry::getKey,
                                              Map.Entry::getValue)))
                              .body(bodyData).build()));
    }
  };
}
 
Example #14
Source File: FeignErrorDecoderFactoryTests.java    From spring-cloud-openfeign with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomErrorDecoderFactory() {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
			SampleConfiguration2.class);
	FeignErrorDecoderFactory errorDecoderFactory = context
			.getBean(FeignErrorDecoderFactory.class);
	assertThat(errorDecoderFactory).isNotNull();
	ErrorDecoder errorDecoder = errorDecoderFactory.create(Object.class);
	assertThat(errorDecoder).isNotNull();
	assertThat(errorDecoder instanceof ErrorDecoderImpl).isTrue();
	context.close();
}
 
Example #15
Source File: AsyncResponseHandler.java    From feign with Apache License 2.0 5 votes vote down vote up
AsyncResponseHandler(Level logLevel, Logger logger, Decoder decoder, ErrorDecoder errorDecoder,
    boolean decode404, boolean closeAfterDecode) {
  super();
  this.logLevel = logLevel;
  this.logger = logger;
  this.decoder = decoder;
  this.errorDecoder = errorDecoder;
  this.decode404 = decode404;
  this.closeAfterDecode = closeAfterDecode;
}
 
Example #16
Source File: SynchronousMethodHandler.java    From feign with Apache License 2.0 5 votes vote down vote up
public MethodHandler create(Target<?> target,
                            MethodMetadata md,
                            RequestTemplate.Factory buildTemplateFromArgs,
                            Options options,
                            Decoder decoder,
                            ErrorDecoder errorDecoder) {
  return new SynchronousMethodHandler(target, client, retryer, requestInterceptors, logger,
      logLevel, md, buildTemplateFromArgs, options, decoder,
      errorDecoder, decode404, closeAfterDecode, propagationPolicy, forceDecoding);
}
 
Example #17
Source File: SynchronousMethodHandler.java    From feign with Apache License 2.0 5 votes vote down vote up
private SynchronousMethodHandler(Target<?> target, Client client, Retryer retryer,
    List<RequestInterceptor> requestInterceptors, Logger logger,
    Logger.Level logLevel, MethodMetadata metadata,
    RequestTemplate.Factory buildTemplateFromArgs, Options options,
    Decoder decoder, ErrorDecoder errorDecoder, boolean decode404,
    boolean closeAfterDecode, ExceptionPropagationPolicy propagationPolicy,
    boolean forceDecoding) {

  this.target = checkNotNull(target, "target");
  this.client = checkNotNull(client, "client for %s", target);
  this.retryer = checkNotNull(retryer, "retryer for %s", target);
  this.requestInterceptors =
      checkNotNull(requestInterceptors, "requestInterceptors for %s", target);
  this.logger = checkNotNull(logger, "logger for %s", target);
  this.logLevel = checkNotNull(logLevel, "logLevel for %s", target);
  this.metadata = checkNotNull(metadata, "metadata for %s", target);
  this.buildTemplateFromArgs = checkNotNull(buildTemplateFromArgs, "metadata for %s", target);
  this.options = checkNotNull(options, "options for %s", target);
  this.propagationPolicy = propagationPolicy;

  if (forceDecoding) {
    // internal only: usual handling will be short-circuited, and all responses will be passed to
    // decoder directly!
    this.decoder = decoder;
    this.asyncResponseHandler = null;
  } else {
    this.decoder = null;
    this.asyncResponseHandler = new AsyncResponseHandler(logLevel, logger, decoder, errorDecoder,
        decode404, closeAfterDecode);
  }
}
 
Example #18
Source File: Issue362Tests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Override
public Exception decode(String methodKey, Response response) {
	this.feignComponentAsserter.executedComponents.put(ErrorDecoder.class, true);
	if (response.status() == 409) {
		return new RetryableException(response.status(), "Article not Ready",
				Request.HttpMethod.GET, new Date(), response.request());
	}
	else {
		return super.decode(methodKey, response);
	}
}
 
Example #19
Source File: VertxFeign.java    From feign-vertx with Apache License 2.0 5 votes vote down vote up
private ParseHandlersByName(
    final Contract contract,
    final HttpClientOptions options,
    final Encoder encoder,
    final Decoder decoder,
    final ErrorDecoder errorDecoder,
    final AsynchronousMethodHandler.Factory factory) {
  this.contract = contract;
  this.options = options;
  this.factory = factory;
  this.errorDecoder = errorDecoder;
  this.encoder = encoder;
  this.decoder = decoder;
}
 
Example #20
Source File: FeignErrorDecoderFactoryTests.java    From spring-cloud-openfeign with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomErrorDecoderFactoryNotOverwritingErrorDecoder() {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
			SampleConfiguration3.class);
	FeignErrorDecoderFactory errorDecoderFactory = context
			.getBean(FeignErrorDecoderFactory.class);
	assertThat(errorDecoderFactory).isNotNull();
	ErrorDecoder errorDecoderFromFactory = errorDecoderFactory.create(Object.class);
	assertThat(errorDecoderFromFactory).isNotNull();
	assertThat(errorDecoderFromFactory instanceof ErrorDecoderImpl).isTrue();
	ErrorDecoder errorDecoder = context.getBean(ErrorDecoder.class);
	assertThat(errorDecoder).isNotNull();
	assertThat(errorDecoder instanceof ErrorDecoder.Default).isTrue();
	context.close();
}
 
Example #21
Source File: TransactionFeignErrorDecoder.java    From ByteJTA with GNU Lesser General Public License v3.0 4 votes vote down vote up
public feign.codec.ErrorDecoder getDelegate() {
	return delegate;
}
 
Example #22
Source File: CompensableFeignErrorDecoder.java    From ByteTCC with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void setDelegate(feign.codec.ErrorDecoder delegate) {
	this.delegate = delegate;
}
 
Example #23
Source File: Issue362Tests.java    From spring-cloud-sleuth with Apache License 2.0 4 votes vote down vote up
@Bean
public ErrorDecoder errorDecoder(FeignComponentAsserter feignComponentAsserter) {
	return new CustomErrorDecoder(feignComponentAsserter);
}
 
Example #24
Source File: SpringCloudConfiguration.java    From ByteJTA with GNU Lesser General Public License v3.0 4 votes vote down vote up
@org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean(feign.codec.ErrorDecoder.class)
@org.springframework.context.annotation.Bean
public feign.codec.ErrorDecoder errorDecoder() {
	return new ErrorDecoder.Default();
}
 
Example #25
Source File: SpringCloudConfiguration.java    From ByteJTA with GNU Lesser General Public License v3.0 4 votes vote down vote up
@org.springframework.context.annotation.Primary
@org.springframework.context.annotation.Bean
public feign.codec.ErrorDecoder transactionErrorDecoder(@Autowired feign.codec.ErrorDecoder decoder) {
	return new TransactionFeignErrorDecoder(decoder);
}
 
Example #26
Source File: TransactionFeignErrorDecoder.java    From ByteJTA with GNU Lesser General Public License v3.0 4 votes vote down vote up
public TransactionFeignErrorDecoder(feign.codec.ErrorDecoder decoder) {
	this.delegate = decoder;
}
 
Example #27
Source File: FeignClientFactoryBean.java    From spring-cloud-openfeign with Apache License 2.0 4 votes vote down vote up
protected void configureUsingProperties(
		FeignClientProperties.FeignClientConfiguration config,
		Feign.Builder builder) {
	if (config == null) {
		return;
	}

	if (config.getLoggerLevel() != null) {
		builder.logLevel(config.getLoggerLevel());
	}

	if (config.getConnectTimeout() != null && config.getReadTimeout() != null) {
		builder.options(new Request.Options(config.getConnectTimeout(),
				config.getReadTimeout()));
	}

	if (config.getRetryer() != null) {
		Retryer retryer = getOrInstantiate(config.getRetryer());
		builder.retryer(retryer);
	}

	if (config.getErrorDecoder() != null) {
		ErrorDecoder errorDecoder = getOrInstantiate(config.getErrorDecoder());
		builder.errorDecoder(errorDecoder);
	}

	if (config.getRequestInterceptors() != null
			&& !config.getRequestInterceptors().isEmpty()) {
		// this will add request interceptor to builder, not replace existing
		for (Class<RequestInterceptor> bean : config.getRequestInterceptors()) {
			RequestInterceptor interceptor = getOrInstantiate(bean);
			builder.requestInterceptor(interceptor);
		}
	}

	if (config.getDecode404() != null) {
		if (config.getDecode404()) {
			builder.decode404();
		}
	}

	if (Objects.nonNull(config.getEncoder())) {
		builder.encoder(getOrInstantiate(config.getEncoder()));
	}

	if (Objects.nonNull(config.getDecoder())) {
		builder.decoder(getOrInstantiate(config.getDecoder()));
	}

	if (Objects.nonNull(config.getContract())) {
		builder.contract(getOrInstantiate(config.getContract()));
	}

	if (Objects.nonNull(config.getExceptionPropagationPolicy())) {
		builder.exceptionPropagationPolicy(config.getExceptionPropagationPolicy());
	}
}
 
Example #28
Source File: OpenFeignAutoConfiguration.java    From summerframework with Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public ErrorDecoder feignErrorDecoder() {
    return new ApiErrorDecoder();
}
 
Example #29
Source File: TransactionFeignErrorDecoder.java    From ByteJTA with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void setDelegate(feign.codec.ErrorDecoder delegate) {
	this.delegate = delegate;
}
 
Example #30
Source File: ClientConfiguration.java    From tutorials with MIT License 4 votes vote down vote up
@Bean
public ErrorDecoder errorDecoder() {
    return new ErrorDecoder.Default();
}