I have a D3 project that uses a very large CSV file to read the data. It works fine except sometimes user sees the spinning loading image indefinitely because of one the following issues.
I need to be able to catch these issues and display some meaningful message to user rather than the never-ending wait message:
- When the data file (MyData.csv) doesn’t exist
- When the MyData.csv exists but is empty
- When the MyData.csv exists, is not empty but is improperly formatted (change the name of a column header on first row for testing).
Ideally, I would like to be able to distinguish among them.
function loadData() {
d3.csv('MyMap.csv', function(data) {
data.forEach(function(d) {
doSomething()
});
// load primary data set
d3.csv('MyData.csv', function (data) {
doSomethingWithData(data);
}); // main data set
});
};
Updated with error checking
var ErrorEnum = Object.freeze({NOTFOUND: 1, EMPTY: 2, INVALIDFORMAT: 3});
var mapFileName = 'MyMap_empty.csv';
var dataFileName = 'MyData_empty.csv';
function redirectOnFileError(fileName, url, errID) {
var errTitle = errID == ErrorEnum.NOTFOUND ? "File Not Found" : (errID == ErrorEnum.EMPTY ? "Empty File" : "Invalid File Format");
var errText = fileName + (errID == ErrorEnum.NOTFOUND ? " could not be found" : (errID == ErrorEnum.EMPTY ? " is empty" : " has invalid format"));
console.log(errText);
swal({
title: errTitle,
text: errText,
type: "error",
confirmButtonText: "OK"
},
function(isConfirm){
// somehow we never get here!
console.log("here ...");
if (isConfirm) {
window.location.href = url;
}
});
// hack ... callback function above is not executed, so using below jQuery to use "OK" button's class and 'click' it
$('.swal2-confirm').click(function(){
window.location.href = url;
});
}
function loadData() {
d3.csv(mapFileName, function (error, data) {
if (error && error.status === 404) {
redirectOnFileError(mapFileName, "fnf.html", ErrorEnum.NOTFOUND);
}
else if (data.length === 0) {
redirectOnFileError(mapFileName, "ef.html", ErrorEnum.EMPTY);
}
else {
data.forEach(function (d) {
// DoSomethingHere();
});
// load primary data set
d3.csv(dataFileName, function (error, data) {
if (error && error.status === 404) {
redirectOnFileError(dataFileName, "fnf.html", ErrorEnum.NOTFOUND);
}
else if (data.length === 0) {
redirectOnFileError(dataFileName, "ef.html", ErrorEnum.EMPTY); }
else {
// DomSomethingWithData();
}); // main data set
});
}
}
};