I have the following code that calls an API, and caches the result (so it be used multiple times):
var requestCache = {};
function LoadDataFromApi(apiUrl) {
if (!requestCache[apiUrl]) {
requestCache[apiUrl] = $.ajax({
type: 'GET',
url: apiUrl,
dataType: "json"
});
}
return requestCache[apiUrl];
}
On occasions, the API throws an exception, which I'm trying to catch and display. According to the Firefox debugger, when an exception occurs, the response data looks like this:
{
"Message":"An error has occurred.",
"ExceptionMessage":"Invalid object name 'Foo_Bar'.",
"ExceptionType":"System.Data.SqlClient.SqlException",
}
From the JQuery documentation, I see there's a statusCode
object within $.ajax
, but I cannot successfully implement this. An answer here is close, but doesn't actually retrieve the exception message.
From various searches today, I've got this far, but the JSON doesn't parse, and I don't know where the problem lies because the JSON parses okay when used elsewhere:
function LoadDataFromApi(apiUrl) {
if (!requestCache[apiUrl]) {
requestCache[apiUrl] = $.ajax({
type: 'GET',
url: apiUrl,
dataType: "json",
statusCode: {
500: function (json) {
var j = JSON.parse(json);
alert(j.Message);
}
}
});
}
return requestCache[apiUrl];
}
I'd be grateful if anyone could spot the issue in my code please?