Spring Boot : How to pass errors through JSON response?

Tuuchen :

I have a very basic OpenWeathermap app made with Spring Boot, and when city is not found, OpenWeathermap returns {"cod":"404","message":"city not found"}, but I can't pass this from backend to my frontend as JSON. My frontend response is just Error: Request failed with status code 500.

I'm handling the responses from backend to frontend as JSON object and parsing the weather data at front.

My Controller looks like this

@RestController
@RequestMapping("/backend")
public class Controller {

    @GetMapping("/{CITY}")
    public @ResponseBody Object getWeather(@PathVariable String CITY) {

        Object response = WeatherAPI.getCity(CITY);
        return response;
    }

and my WeatherAPI class looks like this

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;
    }
}

I tried for example this: https://mkyong.com/spring-boot/spring-rest-error-handling-example/ and modified my code like this:

return response.orElseThrow(() -> new NotFoundException());, but it says .orElseThrow is undefined for the type

How can I pass the "city not found" error with the right status code to my frontend?

Alex :

RestTemplate will throw an exception for any error responses. You can surround the template.getForEntity call in a try-catch block and handle the exceptions, returning the message in any format you want.

The exception you are looking for is HttpStatusCodeException.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12083&siteId=1