我开发了一个Spring Boot项目,我使用ExceptionHandler以@RestControllerAdvice
注释捕获所有异常。 服务器端没有问题来捕获异常。 但是,我不知道如何在客户端应用程序中捕获这些异常。来自客户端的Springboot ExceptionHandler catch
请问您能帮我吗?
我开发了一个Spring Boot项目,我使用ExceptionHandler以@RestControllerAdvice
注释捕获所有异常。 服务器端没有问题来捕获异常。 但是,我不知道如何在客户端应用程序中捕获这些异常。来自客户端的Springboot ExceptionHandler catch
请问您能帮我吗?
如果你使用spring-web的RestTemplate
,这里有一个例子:
try {
ResponseEntity<String> response = new RestTemplate().getForEntity(url, String.class);
System.out.println("Response: " + response.getBody());
} catch (HttpStatusCodeException e) {
System.err.println("Problem querying " + url + ". " +
"Status code " + e.getStatusCode() +
" and error message " + e.getResponseBodyAsString());
}
注意RestTemplate
默认会抛出一个异常错误状态代码,所以你需要捕捉HttpStatusCodeException
。
虽然并不是所有的错误都是HttpStatusCodeException
,但它们全都有RestClientException
作为父母,如果确实需要的话也可以抓住它。
非常感谢您的帮助,它解决了我的问题。 – tester
在客户端,大概是使用HTTP客户端(例如Spring的RestTemplate
或Apache Commons的HttpClient
)。事情是这样的,也许:
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
鉴于此代码,HTTP状态和响应主体可用如下:
HttpStatus httpStatus = response.getStatusCode();
String responseBody = response.getBody();
所以,无论状态码和响应主体您通过RestControllerAdvice
提供能被读出来的回应。
一个典型的方法是评估HttpStatus是否是200
,如果它不属于异常处理块,则使用响应主体来了解异常的性质。
谢谢毛刺,你的解决方案节省我的一天。 – tester
你在使用什么客户端? RestTemplate? – Gondy
是的RestTemplate – tester
然后在使用RestTemplate时只使用try-catch块。捕获RestClientException并根据需要处理它。 – Gondy