java - 通过spring rest模板获取异常的堆栈跟踪
问题描述
我有 2 项服务 -Service 1
和Service 2
. 通过 Spring Rest TemplateService 1
调用一些API。Service 2
现在发生了一些异常Service 2
。我需要它的整个堆栈跟踪Service 1
。如何得到它?
Service 1 ---calls--> Service 2
Service 1
堆栈跟踪是否甚至被 Spring传递给?
你可以说我这样打电话:
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
return restTemplate.exchange("http://localhost:8080/products", HttpMethod.GET, entity, String.class).getBody();
解决方案
我需要它在服务 1 中的整个堆栈跟踪。如何获得它?
所以有办法得到它,本质上你必须实施。
您可以从中获取相关的异常消息/跟踪JSON response
。Service 2
也就是当end有anyexception
时Service 2
,我们可以配置response来发送相关的异常信息。
在这篇文章中,有3 个答案解释了不同的实现方式,也是这个。从今起 :
堆栈跟踪是否甚至被 Spring 传递给 Service 1 ?
通常exception
在处理 a 时抛出的任何未处理/运行时web-request
都会导致服务器返回HTTP 500
响应。
所以答案是 spring 不会转移堆栈跟踪,Service 1
而是以错误HTTP 500
和最可能的消息来响应您的exception
.
但是,您自己编写的任何异常都可以使用注解进行@ResponseStatus
注解(它支持规范定义的所有 HTTP 状态代码HTTP
)。
当annotated exception
从控制器方法抛出 an 并且未在其他地方处理时,它将自动导致适当HTTP response
的返回,并带有指定的状态代码和写入的消息/跟踪。例如,
@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Account") // 404
public class AddressNotFoundException extends RuntimeException {
// ...
}
这是一个使用它的控制器方法:
@RequestMapping(value="/account/{id}", method=GET)
public String showOrder(@PathVariable("id") long id, Model model) {
Account account = accountServices.findAccountById(id);
if (account == null) throw new AddressNotFoundException(id);
model.addAttribute(account);
return "accountDetail";
}
HTTP 404
如果此方法处理的 URL 包含未知的帐户 ID,将返回熟悉的响应。
希望这可以帮助。
推荐阅读
- git - git fetch 失败并显示“致命:git upload-pack: not our ref a639 ...”并第二次成功
- css - CSS 选择器中的泛化是可能的吗?
- json - 如何在postgresql中存储和打印来自json对象的数组值?
- pdfbox - 为什么预告片对象报告“大小”条目的先前值?
- sql - Dense Rank 显示不正确的值
- kubernetes - 如何为领事公开入口
- jquery - AJAX 调用向控制器发送空参数
- azure-devops - DevOps 组织未出现在我的帐户中
- ios - 我如何解析自定义 JSON 数据
- vb.net - 如何使用递归提取 ContextMenuStrip 的所有 ToolStripMenuItems?