首页 > 解决方案 > 通过spring rest模板获取异常的堆栈跟踪

问题描述

我有 2 项服务 -Service 1Service 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();

标签: javaspringspring-bootspring-mvcresttemplate

解决方案


我需要它在服务 1 中的整个堆栈跟踪。如何获得它?

所以有办法得到它,本质上你必须实施。 您可以从中获取相关的异常消息/跟踪JSON responseService 2也就是当end有anyexceptionService 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,将返回熟悉的响应。

希望这可以帮助。


推荐阅读