2

I would like to understand how to do with the following,

I have a microservice who need to get a product:

    @RequestMapping("/details-produit/{id}")
    public String ficheProduit(@PathVariable int id,  Model model){

      ResponseEntity<ProductBean> produit = ProduitsProxy.recupererUnProduit(id);
      model.addAttribute("produit", produit.getBody());

        return "FicheProduit";
    }

my feign class:

    @GetMapping( value = "/Produits/{id}")
    ResponseEntity<ProductBean> recupererUnProduit(@PathVariable("id") int id);

And my CustomErrorDecoder:

    @Override
    public Exception decode(String invoqueur, Response reponse) {

        if (reponse.status() == 400) {
            return new ProductBadRequestException("Requête incorrecte ");
        } else if (reponse.status() == 404) {
            return new ProductNotFoundException("Produit non trouvé ");
        }

        return defaultErrorDecoder.decode(invoqueur, reponse);
    }

What I would like to understand it's, how to get back to the caller method for do like this:


    @RequestMapping("/details-produit/{id}")
    public String ficheProduit(@PathVariable int id,  Model model){

ResponseEntity<ProductBean> productBeanResponseEntity = ProduitsProxy.recupererUnProduit(id);

        if (productBeanResponseEntity.getStatusCode() == HttpStatus.OK) {
            model.addAttribute("produit", productBeanResponseEntity.getBody());          
        } else {
            **// Do something here**
        }
        return "FicheProduit";
    }

For the moment, the only wawy I found was to do like this :

        try {

            ResponseEntity<ProductBean> produit = ProduitsProxy.recupererUnProduit(id);

            model.addAttribute("produit", produit.getBody());
        } catch (ProductNotFoundException e) {
            log.error(e.getMessage());
        }


But I would like to handle of kind of error and continue the process of the caller method.

How can I handle it ?

Thanks !

Joffrey Bonifay
  • 93
  • 1
  • 10

1 Answers1

0

You can write method which will catch exceptions or return product. Also it's not necessary to get ResponseEntity return type into feign client for no special reason. Snippets below:

@GetMapping(value = "/Produits/{id}")
ProductBean recupererUnProduit(@PathVariable("id") int id);
private ProductBean getProduct(int productId) {
   try {
       return produitsProxy.recupererUnProduit(productId);
   } catch (ProductNotFoundException e) {
       log.error(e.getMessage());
   }
}
mrklg
  • 1
  • I tried with this, but the problem is that feign request can have others exception like connection refused or others, I wanted to avoid a big try catch with all the exception that can be thrown – Joffrey Bonifay Jan 13 '20 at 22:11