私は春ブーツで作られた非常に基本的なOpenWeathermapアプリを持っている、と市が見つからない場合、OpenWeathermap戻り{"cod":"404","message":"city not found"}
ますが、私はバックエンドからJSONとしての私のフロントエンドにこれを渡すことはできません。私のフロントエンドの応答だけですError: Request failed with status code 500
。
私は、JSONオブジェクトとしてバックエンドからフロントエンドへの応答を処理し、前面に気象データを解析しています。
私のController
このようになります
@RestController
@RequestMapping("/backend")
public class Controller {
@GetMapping("/{CITY}")
public @ResponseBody Object getWeather(@PathVariable String CITY) {
Object response = WeatherAPI.getCity(CITY);
return response;
}
そして、私のWeatherAPI
クラスでは、このようになります
public class WeatherAPI {
public static Object getCity(String CITY) {
RestTemplate template = new RestTemplate();
ResponseEntity<Object> response = template.getForEntity("https://api.openweathermap.org/data/2.5/weather?q=" + CITY + "&units=metric&lang=fi&appid=" + API-KEY-HERE, Object.class);
return response;
}
}
私は、例えば、この試みた:https://mkyong.com/spring-boot/spring-rest-error-handling-example/をし、このように私のコードを変更しました:
return response.orElseThrow(() -> new NotFoundException());
が、それは言います .orElseThrow is undefined for the type
どのように私は私のフロントエンドに右の状態コードでエラーが見つかりません「都市」を渡すことができますか?
RestTemplateは、任意のエラー応答のための例外がスローされます。あなたは囲むことができますtemplate.getForEntity
try-catchブロックでコールをし、例外を処理、あなたが望む任意の形式でメッセージを返します。
あなたが探しているの例外がありますHttpStatusCodeException
。