2

我想了解如何处理以下内容,

我有一个需要获取产品的微服务:

    @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";
    }

我的假装课:

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

还有我的 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);
    }

我想了解的是,如何回到调用者方法做这样的事情:


    @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";
    }

目前,我发现的唯一方法是这样做:

        try {

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

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


但我想处理一种错误并继续调用者方法的过程。

我该如何处理?

谢谢 !

4

1 回答 1

0

您可以编写将捕获异常或返回产品的方法。此外,没有特殊原因,也没有必要将 ResponseEntity 返回类型放入 feign 客户端。以下片段:

@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());
   }
}
于 2020-01-13T20:59:42.693 回答