How to handle JSON error message

I am a complete newbie with JavaScript and jQuery.

When I request my API, I usually get JSON as follows:

{ "soc": 9271, "series": [ { "year": 2013, "estpay": 370 }, { "year": 2012, "estpay": 430 } ] } 

However, if my request is invalid, I will get JSON as follows:

 { "error": "Some message here . . . .." } 

So my question is: what is the syntax for detecting an error message and then setting the response type to IF / ELSE? those. if the error message does this. If the error message does not do something else.

+5
source share
7 answers

You can try using a implemented JSON tool that has built-in methods.

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

+1
source

check if there is a first error

 // assume response is received as string var data = JSON.parse(response) ... if (data.error) { // handle error console.log(data.error); return; } // handle code normally ... 
+1
source
 var o = JSON.parse(response); if('error' in o){ // error in response } 
0
source

Suppose the JSON object is stored in the result variable.

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 !"); } 
0
source

Checking for the error key in your response data will do the job until now, but in order for your API to comply with the REST protocol and more scalable / dynamic, I would base the error handling on the HTTP status code and messages. You can refer to this list to find out what the valid answer is and what each status code means. https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

Here is a quick example of how to handle status code in jQuery:

 $.ajax({ statusCode: { 500: function(xhr) { if(window.console) console.log(xhr.responseText); } } }); 

In addition, you should also parse JSON to see if this is true, for example, Michael Ido suggested

0
source

It can be a good structure.

 try { data = JSON.parse(response); } catch(e) { data = false; } if(!data || data.error) { // handel error } else { // data is good } 
0
source

Thanks for the very quick answers. I tried to implement your suggestions, but I fail because of the lack of knowledge of newcomers. I gave an 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 an โ€œerrorโ€ appears, 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>") }); 
-1
source

Source: https://habr.com/ru/post/1246123/


All Articles