servo
servo

Reputation: 55

Yahoo Weather API - Handling Bad Location Input String | Node.JS/Express

I'm very new to APIs, but I've been fairly successful experimenting with a custom weather page that's powered by Yahoo's Weather API. The problem is with the handling of bad input. If an end user submits a location string that's not considered acceptable for whatever reason, the response is a blank page with nothing but the words "Internal Server Error". I'm trying to do an if/else check for an undefined response object but the app keeps moving forward regardless. Here's my code:

   request.get(
            'https://weather-ydn-yql.media.yahoo.com/forecastrss?location=' + location + '&format=json',
            null,
            null,
            function (err, data, result) {
                if (err) {
                    console.log(err);
                    return;
                } else {
                    let parsedData = JSON.parse(data); 
                    if (parsedData === undefined) { // this doesn't catch it
                        // stop app and throw some sort of error
                    } else {
                         ...// continue running app
                    }

Here's the internal console error I keep getting back if bad input is submitted:

TypeError: /workspace/web-dev-workshop/YahooWeatherAPI/YahooWeatherApp/views/home.ejs:29
    27| <% } %> 
    28| 
 >> 29| <% weatherCode = parsedData["current_observation"]["condition"]["code"]; %>
    30| 
    31| <!-- Location Form -->
    32|     <section id="location">

Cannot read property 'code' of undefined

Looking for some suggestions on how I can have the page do nothing at all and just refresh with a blank input field so the end user can try again, or possibly forward them to an error page with a link to go back and try again? Whatever's easiest. -Thanks in advance for any helpful tips you can provide, guys.

Upvotes: 0

Views: 52

Answers (1)

djs
djs

Reputation: 4065

You are checking this:

if (parsedData === undefined)

But right above that, you explicitly define parsedData to whatever comes back from JSON.parse():

let parsedData = JSON.parse(data); 

So, parsedData will be whatever results from calling JSON.parse() on your data, which I imagine must be something. Find out what that something is in the event of a malformed request to Yahoo's API, and you can check for that.

Upvotes: 0

Related Questions