【发布时间】:2020-02-23 13:02:45
【问题描述】:
我有一个使用 Spring Boot 制作的非常基本的 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
如何将带有正确状态代码的“未找到城市”错误传递给我的前端?
【问题讨论】:
-
您不应混合使用
@RestController、@ResponseBody和ResponseEntity<Object>。@RestController在类中的所有 REST 端点上暗示@ResponseBody。@ResponseBody和ResponseEntity<Object>互斥,不能同时使用。我建议检查控制器方法是否引发了异常。如果不是,则删除@RestController和@ResponseBody两者。
标签: java spring spring-boot