I have an API which will return a failure in form of custom response message, while still sending a Http 200 response. Example:
Status: 200
Body: {
"code":404,
"message":"Data not found",
"data":{},
"status":"ERROR"
}
My current implementeation of the ErrorDecoder:
public class ApiFeignErrorDecoder implements ErrorDecoder {
private final Gson gson;
public ApiFeignErrorDecoder(Gson gson) {
this.gson = gson;
}
@Override
public Exception decode(String methodKey, Response response) {
try {
ApiResponse apiResponse = gson.fromJson(response.body().asReader(), BaseApiResponse.class);
ResponseStatus status = apiResponse.getStatus();
switch (status) {
case SUCCESS:
return null;
case FAIL:
return new Exception("Failure message recorded");
case ERROR:
return new Exception("Error message recorded");
default:
return new Exception("No suitable status found.");
}
} catch (IOException e) {
e.printStackTrace();
return new ErrorDecoder.Default().decode(methodKey, response);
}
}
}
The problem I have is Feign/Spring will only switch into the ErrorDecoder if the HttpStatus is > 300. The JavaDocs from the error decoder also describe this limitation:
"Error handling Responses where Response.status() is not in the 2xx range are classified as errors,addressed by the ErrorDecoder. That said, certain RPC apis return errors defined in the Response.body() even on a 200 status. For example, in the DynECT api, a job still running condition is returned with a 200 status, encoded in json. When scenarios like this occur, you should raise an application-specific exception (which may be retryable)."
My question now is what/how exactly can I implement these or is there a way to extend the ErrorDecoder in such a way that I will be able to handle these error messages. I think I should be able to put them into the either the Decoder or even Implement/override the HttpClient but I'm not sure what the correct/best way is.