2121import feign .Logger ;
2222import feign .Param ;
2323import feign .RequestLine ;
24+ import feign .Response ;
25+ import feign .codec .Decoder ;
26+ import feign .codec .ErrorDecoder ;
2427import feign .gson .GsonDecoder ;
2528
2629/**
2932public class GitHubExample {
3033
3134 public static void main (String ... args ) throws InterruptedException {
35+ Decoder decoder = new GsonDecoder ();
3236 GitHub github = Feign .builder ()
33- .decoder (new GsonDecoder ())
37+ .decoder (decoder )
38+ .errorDecoder (new GitHubErrorDecoder (decoder ))
3439 .logger (new Logger .ErrorLogger ())
3540 .logLevel (Logger .Level .BASIC )
3641 .target (GitHub .class , "https://api.github.com" );
@@ -40,6 +45,12 @@ public static void main(String... args) throws InterruptedException {
4045 for (Contributor contributor : contributors ) {
4146 System .out .println (contributor .login + " (" + contributor .contributions + ")" );
4247 }
48+
49+ try {
50+ contributors = github .contributors ("netflix" , "some-unknown-project" );
51+ } catch (GitHubClientError e ) {
52+ System .out .println (e .error .message );
53+ }
4354 }
4455
4556 interface GitHub {
@@ -53,4 +64,51 @@ static class Contributor {
5364 String login ;
5465 int contributions ;
5566 }
67+
68+ static class ClientError {
69+
70+ String message ;
71+ List <Error > errors ;
72+ }
73+
74+ static class Error {
75+ String resource ;
76+ String field ;
77+ String code ;
78+ }
79+
80+ static class GitHubErrorDecoder implements ErrorDecoder {
81+
82+ final Decoder decoder ;
83+ final ErrorDecoder defaultDecoder = new ErrorDecoder .Default ();
84+
85+ public GitHubErrorDecoder (Decoder decoder ) {
86+ this .decoder = decoder ;
87+ }
88+
89+ public Exception decode (String methodKey , Response response ) {
90+ if (response .status () >= 400 && response .status () < 500 ) {
91+ try {
92+ ClientError error = (ClientError ) decoder .decode (response , ClientError .class );
93+ return new GitHubClientError (response .status (), error );
94+ } catch (Exception e ) {
95+ e .printStackTrace ();
96+ }
97+ }
98+ return defaultDecoder .decode (methodKey , response );
99+ }
100+ }
101+
102+ static class GitHubClientError extends RuntimeException {
103+
104+ private static final long serialVersionUID = 0 ;
105+
106+ ClientError error ;
107+
108+ protected GitHubClientError (int status , ClientError error ) {
109+ super ("client error " + status );
110+ this .error = error ;
111+ }
112+
113+ }
56114}
0 commit comments