错误处理概述 - try/catch
ccxt采用各种语言中原生的异常机制进行错误处理。
要处理错误,你需要使用try代码块来保护调用ccxt统一API的代码, 然后使用catch代码块捕捉异常。示例代码如下。
JavaScript:
// try to call a unified method
try {
const response = await exchange.fetchTicker ('ETH/BTC')
console.log (response)
} catch (e) {
// if the exception is thrown, it is "caught" and can be handled here
// the handling reaction depends on the type of the exception
// and on the purpose or business logic of your application
if (e instanceof ccxt.NetworkError) {
console.log (exchange.id, 'fetchTicker failed due to a network error:', e.message)
// retry or whatever
// ...
} else if (e instanceof ccxt.ExchangeError) {
console.log (exchange.id, 'fetchTicker failed due to exchange error:', e.message)
// retry or whatever
// ...
} else {
console.log (exchange.id, 'fetchTicker failed with:', e.message)
// retry or whatever
// ...
}
}
Python:
try:
response = await exchange.fetch_order_book('ETH/BTC')
print(response)
except ccxt.NetworkError as e:
print(exchange.id, 'fetch_order_book failed due to a network error:', str(e))
# retry or whatever
# ...
except ccxt.ExchangeError as e:
print(exchange.id, 'fetch_order_book failed due to exchange error:', str(e))
# retry or whatever
# ...
except Exception as e:
print(exchange.id, 'fetch_order_book failed with:', str(e))
# retry or whatever
# ...
PHP:
// try to call a unified method
try {
$response = $exchange->fetch_trades('ETH/BTC');
print_r($response);
} catch (\ccxt\NetworkError $e) {
echo $exchange->id . ' fetch_trades failed due to a network error: ' . $e->getMessage () . "\n";
// retry or whatever
// ...
} catch (\ccxt\ExchangeError $e) {
echo $exchange->id . ' fetch_trades failed due to exchange error: ' . $e->getMessage () . "\n";
// retry or whatever
// ...
} catch (Exception $e) {
echo $exchange->id . ' fetch_trades failed with: ' . $e->getMessage () . "\n";
// retry or whatever
// ...
}