英文:
Extract statusCode and message from exception message
问题
我调用了一个 REST API,并在出现任何异常情况时在表中捕获响应代码和消息。
catch (HttpClientErrorException ex) {
logger.error("调用API时发生HttpClientErrorException");
System.out.println(ex.getStatusCode());
System.out.println(ex.getMessage());
}
输出:
调用API时发生HttpClientErrorException
400 BAD_REQUEST
400: [{"errors":[{"status":"400","code":"1002","title":"缺少参数","detail":"Id 元素是必需的。"}]}]
似乎我可以从 ex.getMessage()
中获取所需的值 StatusCode 和 Message,但是我如何提取这些值呢?
英文:
I am calling a REST API and capturing response code and message in a table in case of any exception occurs.
catch (HttpClientErrorException ex) {
logger.error("HttpClientErrorException occures in calling API");
System.out.println(ex.getStatusCode());
System.out.println(ex.getMessage());
Output:
HttpClientErrorException occures in calling API
400 BAD_REQUEST
400 : [{"errors":[{"status":"400","code":"1002","title":"Missing parameter","detail":"Id element is mandatory."}]}]
It seems I can get the required value StatusCode and Message from ex.getMessage() but how can I extract these values?
答案1
得分: 0
你在 message
属性中看到了从服务器调用的答案,因此格式取决于您正在调用的服务器/端点。
在这种特殊情况下,您可以解析 JSON 并像访问对象并访问所有属性一样使用它。更简单(但更丑陋)的方法是通过正则表达式提取所需内容。
但同样地,您不会有通用的解决方案,因为它取决于服务器的响应。
使用 Jackson
库将其解析为 JSON 的示例:
public class ErrorMessage { // 省略了 getter/setter
String title;
String detail;
String code;
String status;
}
catch (HttpClientErrorException ex) {
logger.error("在调用 API 时发生 HttpClientErrorException");
ObjectMapper objectMapper = new ObjectMapper();
ErrorMessage errorMessage = objectMapper.convertValue(ex.getMessage(), ErrorMessage.class);
System.out.println(errorMessage.getTitle()); // <- 现在您有一个对象,因此可以根据需要进行操作
}
英文:
You see an answer from server being called in message
property, so format depends on server/endpoint you are calling.
In this particular case you can parse JSON and work with it like an object and access all props. Simpler (but uglier) way is to extract all you need by regex.
But again, you will not have universal solution, since it depends on the servers answer.
Parsing as JSON with Jackson
library example:
public class ErrorMessage { // getter/setter are omitted
String title;
String detail;
String code;
String status;
}
catch (HttpClientErrorException ex) {
logger.error("HttpClientErrorException occures in calling API");
ObjectMapper objectMapper = new ObjectMapper();
ErrorMessage errorMessage = objectMapper.convertValue(ex.getMessage(), ErrorMessage.class);
System.out.println(errorMessage.getTitle); // <- you have an object now, so you can do whatever you want
}
答案2
得分: 0
你可以像下面这样使用:
((HttpServerErrorException.InternalServerError)e).getResponseBodyAsString()
这将返回异常消息,不包含错误代码。
英文:
You can use like below:
((HttpServerErrorException.InternalServerError)e).getResponseBodyAsString()
This will give exception message without error code.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论