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);
});