Java Spring引导:如何通过JSON响应传递错误?
我有一个用Spring Boot制作的非常基本的OpenWeathermap应用程序,当找不到city时,OpenWeathermap返回Java Spring引导:如何通过JSON响应传递错误?,java,spring,spring-boot,Java,Spring,Spring Boot,我有一个用Spring Boot制作的非常基本的OpenWeathermap应用程序,当找不到city时,OpenWeathermap返回{“cod”:“404”,“message”:“city not found”},但我不能将它作为JSON从后端传递到前端。我的前端响应只是错误:请求失败,状态代码为500 我以JSON对象的形式处理从后端到前端的响应,并在前端解析天气数据 我的控制器如下所示 @RestController @RequestMapping("/backend") public
{“cod”:“404”,“message”:“city not found”}
,但我不能将它作为JSON从后端传递到前端。我的前端响应只是错误:请求失败,状态代码为500
我以JSON对象的形式处理从后端到前端的响应,并在前端解析天气数据
我的控制器
如下所示
@RestController
@RequestMapping("/backend")
public class Controller {
@GetMapping("/{CITY}")
public @ResponseBody Object getWeather(@PathVariable String CITY) {
Object response = WeatherAPI.getCity(CITY);
return response;
}
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;
}
}
我的WeatherAPI
类如下所示
@RestController
@RequestMapping("/backend")
public class Controller {
@GetMapping("/{CITY}")
public @ResponseBody Object getWeather(@PathVariable String CITY) {
Object response = WeatherAPI.getCity(CITY);
return response;
}
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;
}
}
公共类WeatherAPI{
公共静态对象getCity(字符串城市){
RestTemplate=新的RestTemplate();
ResponseEntity response=template.getForEntity(“https://api.openweathermap.org/data/2.5/weather?q=“+CITY+”&units=metric&lang=fi&appid=“+API-KEY-HERE,Object.class”);
返回响应;
}
}
我尝试了以下示例:并修改了我的代码:
returnresponse.orelsetrow(()->newnotfoundexception())
,但它表示,。OrelsThrow未定义类型
如何将状态代码正确的“未找到城市”错误传递到前端 RestTemplate将为任何错误响应引发异常。您可以在try-catch块中包围
模板.getForEntity
调用,并处理异常,以您想要的任何格式返回消息
您正在查找的异常是
HttpStatusCodeException
RestTemplate将为任何错误响应引发异常。您可以在try-catch块中包围模板.getForEntity
调用,并处理异常,以您想要的任何格式返回消息
您要查找的异常是
HttpStatusCodeException
在调用RestTemplate调用时,实现一个通用的自定义->RestTemplateResponseErrorHandler来处理特定于客户端和服务器的错误
参考:例如使用Spring boot和Spring 5的类似用例。在调用RestTemplate调用时,实现一个通用的自定义->RestTemplateResponseErrorHandler来处理特定于客户端和服务器的错误
参考:举一个使用Spring boot和Spring 5的类似用例的例子。首先,我认为您应该尝试理解@RestController实现。此注释包括简化控制器实现()的@Controller和@ResponseBody注释 其次,您不能使用orElseThrow,因为它是在可选类()下引入的方法。您给出的示例不使用任何可选对象。 我认为您应该正确地研究mkyong链接提供的示例(测试)。您给出的示例与mkyong示例相差太远 对于您的实际问题,您可以按以下方式更改代码: 您可以使用HttpServletResponse类返回所需的状态和错误消息。 您不需要放置@ResponseBody,因为@RestController会自动为您执行此操作
@RestController()
@RequestMapping("/backend")
public class Controller {
@GetMapping("/{city}")
public ResponseObject getWeather(@PathVariable String city, HttpServletResponse response) {
ResponseObject response = WeatherAPI.getCity(city);
if (response == null) {
return response.sendError(HttpStatus.PAGE_NOT_FOUND.value(), "message here");
}
return response;
}
最后,我不确定为什么要使用静态方法作为示例。您应该使用@service为您的WeatherAPI创建服务层。首先,我认为您应该尝试了解@RestController实现。此注释包括简化控制器实现()的@Controller和@ResponseBody注释 其次,您不能使用orElseThrow,因为它是在可选类()下引入的方法。您给出的示例不使用任何可选对象。 我认为您应该正确地研究mkyong链接提供的示例(测试)。您给出的示例与mkyong示例相差太远 对于您的实际问题,您可以按以下方式更改代码: 您可以使用HttpServletResponse类返回所需的状态和错误消息。 您不需要放置@ResponseBody,因为@RestController会自动为您执行此操作
@RestController()
@RequestMapping("/backend")
public class Controller {
@GetMapping("/{city}")
public ResponseObject getWeather(@PathVariable String city, HttpServletResponse response) {
ResponseObject response = WeatherAPI.getCity(city);
if (response == null) {
return response.sendError(HttpStatus.PAGE_NOT_FOUND.value(), "message here");
}
return response;
}
最后,我不确定为什么要使用静态方法作为示例。您应该使用@service为您的WeatherAPI创建服务层。尝试以下方法:
将控制器更新为:
@RestController
@RequestMapping("/backend")
public class Controller {
@GetMapping("/{CITY}")
public ResponseEntity<Object> getWeather(@PathVariable String CITY) {
Object response = WeatherAPI.getCity(CITY);
if(response == null) {
return new ResponseEntity<Object>("city not found", HttpStatus.PAGE_NOT_FOUND);
}
return new ResponseEntity<Object>(response, HttpStatus.OK);
}
}
public class WeatherAPI {
public static Object getCity(String CITY) {
RestTemplate template = new RestTemplate();
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;
}
}
这应该会起到相应的作用。尝试以下方法:
将控制器更新为:
@RestController
@RequestMapping("/backend")
public class Controller {
@GetMapping("/{CITY}")
public ResponseEntity<Object> getWeather(@PathVariable String CITY) {
Object response = WeatherAPI.getCity(CITY);
if(response == null) {
return new ResponseEntity<Object>("city not found", HttpStatus.PAGE_NOT_FOUND);
}
return new ResponseEntity<Object>(response, HttpStatus.OK);
}
}
public class WeatherAPI {
public static Object getCity(String CITY) {
RestTemplate template = new RestTemplate();
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;
}
}
这应该可以相应地工作。您可以使用常规错误处理程序,例如,它可以处理某些特定类型的异常 考虑到这一机制,我们可以通过以下方式调整您的代码:
ControllerAdvice
将知道要发送回客户端的错误代码@ControllerAdvice
公共类GlobalExceptionHandler{
/**在此服务中提供异常处理*/
@异常处理程序({CityWeatherNotFountException.class})
@响应代码(未找到HttpStatus.NOT_)
公共最终响应处理异常(异常示例,WebRequest请求){
公共类WeatherAPI{
公共静态对象getCity(字符串城市){
试一试{
RestTemplate=新的RestTemplate();
ResponseEntity response=template.getForEntity(“https://api.openweathermap.org/data/2.5/weather?q=“+CITY+”&units=metric&lang=fi&appid=“+API-KEY-HERE,Object.class”);
返回响应;}
捕获(restex异常){
抛出新城市天气NOTFOUNTEXCEPTION(ex);}
}
}
您可以使用常规错误处理程序,例如,它可以处理某些特定类型的异常
考虑到这一机制,我们可以