【问题标题】:Feign throw error instead of return ResponseEntity, how to go back to the caller methodFeign抛出错误而不是返回ResponseEntity,如何回到调用者方法
【发布时间】:2020-04-29 12:11:50
【问题描述】:

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

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

    @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());
        }


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

我该如何处理?

谢谢!

【问题讨论】:

    标签: java spring spring-boot spring-cloud-feign java-ee-8


    【解决方案1】:

    您可以编写将捕获异常或返回产品的方法。此外,没有特殊原因,也没有必要将 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());
       }
    }
    

    【讨论】:

    • 我试过这个,但问题是假请求可能有其他异常,如连接被拒绝或其他,我想避免一个大的尝试捕获所有可以抛出的异常
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 2013-09-17
    相关资源
    最近更新 更多