【问题标题】:Error not getting propagated from called service to caller service错误未从被调用服务传播到调用者服务
【发布时间】:2023-04-06 19:51:01
【问题描述】:

我们有 2 个具有 REST 控制器的服务。

调用者服务调用如下:

try {
            response = restTemplate.exchange(urlModifyAttributes, HttpMethod.PUT, new HttpEntity<>(attributesMap, headerMap), parameterizedTypeReference, uriVars);
            return response.getBody();
        } catch (RestClientResponseException e) {
            log.error("Modify attributes failed. Error {}", e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        } catch (Exception e) {
            log.error("Modify attributes failed. Error: {}", e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        }

当被调用的服务抛出 RuntimeException 时:

throw new RuntimeException("Already modified");

但调用者服务无法使用 e.getMessage() 捕获错误消息“已修改”。而是 e.getMessage() 正在返回类似“I/O error on PUT request for http.......” 有没有办法可以在调用者服务级别捕获错误消息?

这两个服务都是 SpringBoot 应用程序并具有 RestControllers

【问题讨论】:

    标签: java spring-boot error-handling runtimeexception


    【解决方案1】:

    您正在调用服务中处理异常,但在被调用服务中它也需要发送异常。对于通用的你可以参考这个或有你自己的自定义实现。

    调用服务:

    @Getmapping("/uri")
    public ResponseEntity<Object> getIt(@RequestBody MyRequest req) {
    try{
    //...business logic
    
        return new ResponseEntity<>(response, HttpStatus.OK);
    
    }catch(MyException e){
        return new ResponseEntity<>(e, HttpStatus.SOME_EXC_STATUS); //or custom exc
    }catch(Exception e){
        return new ResponseEntity<>(e, HttpStatus.SOME_EXC_STATUS);
    }
    }
    

    只有你才能获得异常状态。

    【讨论】:

      【解决方案2】:

      被调用的服务需要在响应中发送这个。你正在打一个休息电话。如果它是一种方法,您也可以从调用者那里捕获它。

      在被调用服务的响应实体中传递异常消息。使用控制器建议或响应状态异常。

      【讨论】:

      • "被调用的服务需要发送这个""这个"是什么意思?
      • 这意味着当您在被调用的服务中捕获该异常时。像这样扔东西。 throw new ResponseStatusException(400, "已经修改"); } 所以你调用的服务将能够读取该消息
      • 不起作用。仍然收到I/O error on PUT request for "http://localhost...: Server returned HTTP response code: 400 for URL: http://localhost...; nested exception is java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost...
      • 分享一点被调用的服务
      猜你喜欢
      • 2011-09-22
      • 1970-01-01
      • 1970-01-01
      • 2020-10-27
      • 2013-06-27
      • 1970-01-01
      • 1970-01-01
      • 2019-04-20
      相关资源
      最近更新 更多