d3.request() 中回撥錯誤處理中的一個或兩個引數
當使用 d3.request()
或其中一個便捷建構函式( d3.json , d3.csv , d3.tsv , d3.html 和 d3.xml )時,有許多錯誤來源。由於網路錯誤,已發出的請求或其響應可能存在問題,或者如果內容格式不正確,則解析可能會失敗。
因此,在傳遞給任何上述方法的回撥中,需要實現一些錯誤處理。為此目的,回撥可以接受兩個引數,第一個是錯誤,如果有的話,第二個是資料。如果在載入或解析過程中發生任何錯誤,則會將有關錯誤的資訊作為第一個引數 error
傳遞,其中 data
為 null
。
d3.json{"some_file.json", function(error, data) {
if (error) throw error; // Exceptions handling
// Further processing if successful
});
無論如何,你沒有義務提供兩個引數。將請求方法與僅具有一個引數的回撥一起使用是完全正確的。為了處理這些型別的回撥,request.js 中有一個私有函式 fixCallback()
,它調整資訊傳遞給方法的單個引數的方式。
function fixCallback(callback) {
return function(error, xhr) {
callback(error == null ? xhr : null);
};
}
對於只有一個引數的所有回撥,D3 將呼叫它,根據定義,該引數是資料。
無論向請求方法的回撥提供了多少引數,data
引數的規則是:
- 如果請求失敗,
data
將是null
- 如果請求成功,
data
將包含載入(和解析)的內容
單引數版本與雙引數版本之間的唯一區別在於提供有關可能發生的錯誤的資訊。如果省略 error
引數,該方法將無聲地失敗,將 data
留作 null
。另一方面,如果將回撥定義為具有兩個引數,則在載入或解析期間有關錯誤的資訊將傳遞給第一個引數,使你能夠適當地處理它。
以下四個對 d3.json
的呼叫演示了現有/不存在檔案與一個引數/兩個引數回撥可能出現的情況:
// FAIL: resource not available or content not parsable
// error contains information about the error
// data will be null because of the error
d3.json("non_existing_file.json", function(error, data) {
console.log("Fail, 2 parameters: ", error, data);
});
// FAIL: resource not available or content not parsable
// no information about the error
// data will be null because of the error
d3.csv("non_existing_file.json", function(data) {
console.log("Fail, 1 parameter: ", data);
});
// OK: resource loaded successfully
// error is null
// data contains the JSON loaded from the resource
d3.json("existing_file.json", function(error, data) {
console.log("OK, 2 parameters: ", error, data);
});
// OK: resource loaded successfully
// no information about the error; this fails silently on error
// data contains the JSON loaded from the resource
d3.json("existing_file.json", function(data) {
console.log("OK, 1 parameter: ", data);
});