Reputation: 71
I am a complete beginner with JavaScript and jQuery.
When I query my API I will normally get JSON like this:
{
"soc": 9271,
"series": [
{
"year": 2013,
"estpay": 370
},
{
"year": 2012,
"estpay": 430
}
]
}
However if my query is invalid I will get JSON like this:
{
"error": "Some message here . . . .."
}
So my question is - what is the syntax to detect the error message and then set up an IF / ELSE type of response? i.e. If error message do this.. If no error message do something else.
Upvotes: 5
Views: 855
Reputation: 71
Thanks for the very quick replies. I have been trying to implement your suggestions but I'm not succeeding due to beginners ignorance. I have put a example of the code that I am working with below.
I just need the JSON from $.get to be checked for the word "error".
If "error" appears then I need var nipay to contain something like "Not available".
Otherwise var nipay = maxBy("year", data.series).estpay
$.get("http://my_api_url",
function(data) {
var nipay = maxBy("year", data.series).estpay ;
$("#box1").html("<p><b>NI:</b> " + nipay + " GBP/week </p>")
});
Upvotes: -1
Reputation: 565
Checking if there is an "error" key in your response data will do the job for now but for the sake of making your API conforming to the REST protocol and more scalable/dynamic I would base the error handling on HTTP status code and messages. You can refer yourself to this list to see what is a valid response and what each status code means. https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
Here's a short example on how to handle the status code in jQuery:
$.ajax({
statusCode: {
500: function(xhr) {
if(window.console) console.log(xhr.responseText);
}
}
});
Additionally, you should also parse the JSON to see if it is valid, like Ido Michael suggested
Upvotes: 0
Reputation: 121
This might be a good structure
try {
data = JSON.parse(response);
} catch(e) {
data = false;
}
if(!data || data.error) {
// handel error
} else {
// data is good
}
Upvotes: 0
Reputation: 1169
Let's assume that the JSON object is stored in the variable result
.
You can try something like this :
var result = JSON.parse(myQuery()); // myQuery() is the function that executes your query
if (result.error) {
alert("Error message here !");
} else {
alert("Hallelujah !");
}
Upvotes: 0
Reputation: 94
check if there's an error first
// assume response is received as string
var data = JSON.parse(response)
...
if (data.error) {
// handle error
console.log(data.error);
return;
}
// handle code normally
...
Upvotes: 1
Reputation: 885
var o = JSON.parse(response);
if('error' in o){
// error in response
}
Upvotes: 0
Reputation: 109
You can try using an implemented JSON tool which has this methods built inside.
secondly you can try and use this:
if (response){
try{
a=JSON.parse(response);
}catch(e){
alert(e); //error in the above string(in this case,yes)!
}
}
Good luck!
Upvotes: 1