转换为对JAVA的响应时的500状态

问题描述

我正在使用Bing API来获取两点之间的距离。 我在项目中添加了正确的数据验证。我想捕获此异常:

enter image description here

所以我想对用户说,嘿,您的目的地地址不正确,请输入正确的地址。

我在应用中使用spring boot。我使用resttemplate。我想将此响应粘贴到String,然后对其进行处理。这是我的代码

{  final String uri = "http://dev.virtualearth.net/REST/V1/Routes/Driving" + "?waypoint.0=ulica" + string1 + "&waypoint.1=ulica" + string2 +
            "&key=" + apiKey;
    String result = "";
    RestTemplate restTemplate = new RestTemplate();
        result = restTemplate.getForObject(uri,String.class);
    }

如您所见,我想在String.class中得到响应。

这是我得到的错误(java在将此响应转换为String时遇到问题,这就是为什么我得到500响应,而不是404响应):

enter image description here

我希望收到Bing的原始回复(而不是500)(我帖子中的第一个SS)。 怎么做?

解决方法

您可以将Bing API调用放在try-catch块中(无论如何,IMHO都是一个好习惯),捕获RestClientExceptionRestClientResponseException并进行处理,例如,通过抛出自己的应用程序异常映射到404响应。例如:

final String uri = "http://dev.virtualearth.net/REST/V1/Routes/Driving" + "?waypoint.0=ulica" + string1 + "&waypoint.1=ulica" + string2 +
       "&key=" + apiKey;
try {
    String result = "";
    RestTemplate restTemplate = new RestTemplate();
    result = restTemplate.getForObject(uri,String.class);
} catch (RestClientResponseException e) {
    if (e.getRawStatusCode() == 404) {
       // Application-specific exception with reasonable meaning and mapping for clients
       throw new UnknownDestinationException(e.getResponseBodyAsString());
    }
    throw e;   // Otherwise just throw it
}
,

这是解决方法:

  // Create needed variables
    final String uri = "http://dev.virtualearth.net/REST/V1/Routes/Driving" + "?waypoint.0=ulica" + string1 + "&waypoint.1=" + string2 +
            "&key=" + bing_api_key;
    String result = "";
    RestTemplate restTemplate = new RestTemplate();
    // Get bing api response
    try {
        result = restTemplate.getForObject(uri,String.class);
    }
    catch (final HttpClientErrorException e) {
        result = e.getResponseBodyAsString();
    }

此行: final HttpClientErrorException e导致我收到404错误,而不是500错误。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...