通过Spring Rest模板获取Exception的堆栈跟踪

Bre*_*min 6 java spring spring-mvc resttemplate spring-boot

我有2个服务- Service 1Service 2。 通过Spring Rest Template Service 1调用一些Service 2API。现在,发生了一些例外情况Service 2。我需要它的整个堆栈跟踪Service 1。如何获得?

Service 1  ---calls--> Service 2
Run Code Online (Sandbox Code Playgroud)

堆栈跟踪是否甚至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();
Run Code Online (Sandbox Code Playgroud)

Viv*_*vek 6

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

因此,有很多方法可以实现它,本质上您必须实现。 你可以让你的相关异常消息/跟踪中JSON responseService 2。也就是说,当末尾有任何内容exceptionService 2,我们可以配置响应以发送相关的异常信息。

这个帖子有3个答案解释不同的方式来实现,也一个。从今起 :

Spring是否甚至将堆栈跟踪传递给服务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 {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

这是使用它的控制器方法:

@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";
}
Run Code Online (Sandbox Code Playgroud)

HTTP 404如果此方法处理的URL包含未知帐户ID,则将返回熟悉的响应。

希望这可以帮助。