6

Still quite inexperienced and I'm trying to error handle a "400 Bad Request".

I have a site with a search bar.
The value entered into the search bar is then placed into an api url that returns an object.
Whenever a misspelled search value is entered, the site's console returns a "400 Bad Request" for the api url.
I also receive the error object below from the api url request.

{
    "meta": {
        "code": 400,
        "errorType": "failed_geocode",
        "errorDetail": "Couldn't geocode param near: Jljjl",
        "requestId": "59208ac96a6071641949481d"
    },
    "response": {}
}

What I want to do is use a conditional statement like below to handle this error:

try {
    if (400 Bad Request) throw "incorrect";
} catch (err) {
    document.getElementById('results').innerHTML = "Input is " + err;
}

I've tried conditional statements like the one's below but it seems like I am unable to access any of the values in the error object that is returned:

if (object.meta.code === 400)
if (object.meta.code !== 200)
if (object === undefined) // or null or 0

How can I put the 400 Bad Request error into the "if statement", or is there another way to handle these errors?
Thanks

6
  • Are you getting back JSON? You may need to parse the response, for example JSON.parse(object) before you can work with it as a JavaScript object. Commented May 27, 2017 at 23:30
  • When you say "getting back JSON", could you elaborate? I'm only receiving the below object when there is an input value error, Thx much: {"meta":{"code":400,"errorType":"failed_geocode","errorDetail":"Couldn't geocode param near: Jljjl","requestId":"59208ac96a6071641949481d"},"response":{}} Commented May 27, 2017 at 23:51
  • The response might be in a string like " {"meta":{"code":400,"errorType":"failed_geocode","errorDetai‌​l":"Couldn't geocode param near: Jljjl","requestId":"59208ac96a6071641949481d"},"response":{}‌​}". If you parse it with JSON.parse(errorObject) what do you get? Commented May 28, 2017 at 0:02
  • I believe the response is not a string. I'm getting an "unexpected token" syntax error when using JSON.parse with the error object. Here is the actual api url that is returning the example error object, if you'd like to view it: api.foursquare.com/v2/venues/… Commented May 28, 2017 at 0:27
  • I see, it looks like that is coming from the body of the response. Are you able to do result.body.meta.code and get the information? Commented May 28, 2017 at 0:30

2 Answers 2

4

Using Fetch API, this could be achieved with the following:

fetch(url)
    .then((res) => {
        if (res.status === 400) {
            throw new Error('your error message here');
        }
        return res.json();
    })
    .then(json => {
        // handle response normally here
    })
    .catch(ex => {
        // handle errors here
    });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much for your help with this, I got everything to work.
3

Just to piggy back off of m1kael this is what I have

window.fetch('https://api.foursquare.com/v2/venues/explore?v=20170324&near=Jljjl&query=study%20spot&limit=10&intent=browse&radius=100000&venuePhotos=1&client_id=XPQI2RJB3NMDT2JYQIMWDMGZSKRDQZX40NYIOKK02DXB1CVE&client_secret=UNHLLMUWXTEI3USTTN5DRJ02QDWQMHZQ5B22CFX0EY4JLEHO')
.then(r => r.json())
.then(r => {
  if (r.meta.code === 400) {
    console.error('Error')
  } else {
    console.log(r)
  }
})

4 Comments

Thanks. I see I was parsing incorrectly, first time trying it. In my site I'm getting the API object using the "$.getJSON" function. So since your last response I've been trying to figure out how to JSON parse my object named "data" within the $.getJSON function.
Looks like $.getJSON does not allow you to handle errors like a 400 response. Looks like you have to use $.ajax. Here is a code pen: codepen.io/arecvlohe/pen/mmYrqq?editors=1011
Inside of the error callback is where you would handle use your conditional logic.
Thanks. I used your answer using fetch and I got it to work with the rest of my code, I've just been studying it a bit. I'm going to study your $.ajax response as well. Thanks for your help. Been working at this problem on my own in my spare time for about a WEEK! Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.