如何从WebApplicationException中获取跨服务调用返回的自定义错误消息
解决方案
可以在服务A中正常获取到该自定义消息,问题出在服务A侧对异常响应实体的读取逻辑不正确。
原因说明
你当前调用e.getResponse().getEntity()拿到的不是直接的字符串内容,而是原始的InputStream输入流对象,直接调用该对象的toString()方法、或者调用异常的getMessage()都无法拿到响应中携带的自定义文本内容。
你控制器B的实现没有问题,已经正确将自定义错误消息放入了400响应的实体中。
实现代码
修改服务A的catch块逻辑,手动读取输入流中的内容即可:
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; // ... 原有代码不变 catch (WebApplicationException e) { Response response = e.getResponse(); StringBuilder errorMsgBuilder = new StringBuilder(); // 读取响应流中的错误信息 try ( InputStream inputStream = (InputStream) response.getEntity(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)) ) { String line; while ((line = reader.readLine()) != null) { errorMsgBuilder.append(line); } } catch (Exception ioEx) { // 流读取失败时兜底取状态码默认描述 errorMsgBuilder.append(response.getStatusInfo().getReasonPhrase()); } String errorMsg = errorMsgBuilder.toString(); // 此处即可拿到自定义的"Invitation is pending"消息 System.out.println("调用服务失败:" + errorMsg); }
简化实现(可选)
如果你的项目中引入了Apache Commons IO工具包,可以直接使用IOUtils简化流读取逻辑:
import org.apache.commons.io.IOUtils; // ... 原有代码不变 catch (WebApplicationException e) { String errorMsg; try { errorMsg = IOUtils.toString((InputStream) e.getResponse().getEntity(), StandardCharsets.UTF_8); } catch (Exception ioEx) { errorMsg = e.getResponse().getStatusInfo().getReasonPhrase(); } System.out.println("调用服务失败:" + errorMsg); }
内容的提问来源于stack exchange,提问作者Jonathan Hagen
相关产品推荐
相关产品推荐

