简体   繁体   中英

How to implement status checking for feign client?

I'm trying to combine 2 or more services and I want to check statuses of them and return custom response. For example one of them returns 200 and the other returns 500, 404, 400 and etc. In this case I want to return empty list. The example below is only valid when all services returning 200

@RestController
@RequiredArgsConstructor
public class Demo3Controller {

    private final Demo1Client demo1Client;
    private final Demo2Client demo2Client;

    @GetMapping("/demo3")
    public String get(){
        return demo1Client.getDemo1() + "&&" + demo2Client.getDemo2();
    }

}

Feign can also return the whole response ( ResponseEntity ), instead of the body object. So, you can refactor your Feign client like this:

@FeignClient
public interface Demo1Client {
    
    public ResponseEntity<String> getDemo1();
}

after that, you can get the status code and body by:

ResponseEntity<String> response = demo1Client.getDemo1();
response.getStatusCodeValue();
response.getBody();

Alternatively, you can catch the FeignException object which has a status code on it and return a correct response object or new exception that is mapped to the explicit error code. That exception will be thrown for any 4XX or 5XX returns. See the docs here: https://appdoc.app/artifact/io.github.openfeign/feign-core/9.3.0/feign/FeignException.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM