title: Spring Boot : How to pass errors through JSON response?
body: <p>I have a very basic OpenWeathermap app made with Spring Boot, and when city is not found, OpenWeathermap returns <code>{"cod":"404","message":"city not found"}</code>, but I can't pass this from backend to my frontend as JSON. My frontend response is just <code>Error: Request failed with status code 500</code>.</p>
  
  <p>I'm handling the responses from backend to frontend as JSON object and parsing the weather data at front. </p>
  
  <p>My <code>Controller</code> looks like this</p>
  
  <pre><code>@RestController
  @RequestMapping("/backend")
  public class Controller {
  
      @GetMapping("/{CITY}")
      public @ResponseBody Object getWeather(@PathVariable String CITY) {
  
          Object response = WeatherAPI.getCity(CITY);
          return response;
      }
  </code></pre>
  
  <p>and my <code>WeatherAPI</code> class looks like this</p>
  
  <pre><code>public class WeatherAPI {
  
      public static Object getCity(String CITY) {
  
          RestTemplate template = new RestTemplate();
          ResponseEntity&lt;Object&gt; response = template.getForEntity("https://api.openweathermap.org/data/2.5/weather?q=" + CITY + "&amp;units=metric&amp;lang=fi&amp;appid=" + API-KEY-HERE, Object.class);
          return response;
      }
  }
  </code></pre>
  
  <p>I tried for example this: <a href="https://mkyong.com/spring-boot/spring-rest-error-handling-example/" rel="nofollow noreferrer">https://mkyong.com/spring-boot/spring-rest-error-handling-example/</a> and modified my code like this:</p>
  
  <p><code>return response.orElseThrow(() -&gt; new NotFoundException());</code>, but it says <code>.orElseThrow is undefined for the type</code></p>
  
  <p>How can I pass the "city not found" error with the right status code to my frontend? </p>