Skip to content

Exception Handling

sonvister edited this page Mar 14, 2018 · 7 revisions

This code demonstrates how to handle exceptions from the IBinanceApi methods.

NOTE: Handling exceptions with this level of precision is only applicable to processes that an application may retry should the first attempt fail (e.g. order placement or withdraw requests).

try
{
    var order = await api.PlaceAsync(user, new MarketOrder()
    {
        Symbol = Symbol.BTC_USDT,
        Side = OrderSide.Sell,
        Quantity = 0.1m
    });
}
catch (OperationCanceledException) // and TaskCanceledException
{
    if (!token.IsCancellationRequested) // or token is not provided.
    {
        // HttpClient timeout (handle same as HTTP 504 response below).
    }

    // Otherwise, canceled by user (ignore).
}
catch (BinanceUnknownStatusException) // ...is BinanceHttpException (w/ status code 504)
{
    // HTTP 504 return code is used when the API successfully sent the message but not get a response within the timeout period.
    // It is important to NOT treat this as a failure; the execution status is UNKNOWN and could have been a success.
}
catch (BinanceHttpException e) // ...is BinanceApiException
{
    // The request failed; handle exception based on HTTP status code.
    if (e.IsClientError())
    {
        // HTTP 4XX return codes are used for for malformed requests; the issue is on the sender's side.
    }
    else if (e.IsServerError())
    {
        // HTTP 5XX return codes are used for internal errors; the issue is on Binance's side.
    }
    else
    {
        // Other HTTP return codes...
    }
}
catch (BinanceApiException)
{
    // Respond to other Binance API exceptions (typically JSON deserialization failures).
}
catch (Exception)
{
    // Other exceptions...
}