# Handling errors

What failures look like: each has a class by family, the API's code, the request id to quote to support, and details.

The whole program, in each language. Set `PHOENIXPERPS_API_KEY` to a sandbox key (`ppk_test_...`) and run it. A write whose outcome is unknown (a timeout) is repeated with the same Idempotency-Key, never a new one.

```typescript
import { randomUUID } from 'node:crypto';
import { NotFoundError, PhoenixPerps, PhoenixPerpsError, RateLimitError, RuleRejectedError, TimeoutError, ValidationError } from '@phoenixperps/sdk';
import type { CreateOrder, Order } from '@phoenixperps/sdk';

const client = new PhoenixPerps();
const [account] = (await client.accounts.list()).data;

function show(err: unknown) {
  if (!(err instanceof PhoenixPerpsError)) throw err;
  console.log(`${err.constructor.name}: ${err.code} (HTTP ${err.status}, ${err.requestId}) ${err.message}`);
  if (err.details) console.log(`  details: ${JSON.stringify(err.details)}`);
  console.log(`  ${err.retryable ? 'may succeed later' : 'will not succeed as it is'}${err.docUrl ? `: ${err.docUrl}` : ''}`);
}

try {
  await client.orders.get(account.id, 'ord_does_not_exist');
} catch (err) {
  if (!(err instanceof NotFoundError)) throw err;
  show(err);
}

try {
  await client.orders.preview(account.id, { market: 'BTC-USD', side: 'buy', type: 'market', size: '0.0000001' });
} catch (err) {
  if (!(err instanceof ValidationError || err instanceof RuleRejectedError)) throw err;
  show(err);
}

// a write that may or may not have happened: the same key again is safe, a new key could place it twice
export async function placeOnce(body: CreateOrder): Promise<Order> {
  const idempotencyKey = randomUUID();
  for (let attempt = 1; ; attempt += 1) {
    try {
      return await client.orders.create(account.id, body, { idempotencyKey });
    } catch (err) {
      if (err instanceof TimeoutError && attempt < 3) continue; // still unknown after the SDK's own retries: same key
      if (err instanceof RateLimitError && err.retryAfter !== null && attempt < 3) {
        await new Promise((r) => setTimeout(r, err.retryAfter ?? 0));
        continue;
      }
      throw err;
    }
  }
}
```

```python
import time
import uuid
from typing import Any, Dict

from phoenixperps import (APITimeoutError, NotFoundError, PhoenixPerps, PhoenixPerpsError, RateLimitError,
                          RuleRejectedError, ValidationError)

client = PhoenixPerps()
account = client.accounts.list().data[0]


def show(err: PhoenixPerpsError) -> None:
    print(f"{type(err).__name__}: {err.code} (HTTP {err.status}, {err.request_id}) {err}")
    if err.details:
        print(f"  details: {err.details}")


try:
    client.orders.get(account["id"], "ord_does_not_exist")
except NotFoundError as err:
    show(err)

try:
    client.orders.preview(account["id"], {"market": "BTC-USD", "side": "buy", "type": "market", "size": "0.0000001"})
except (ValidationError, RuleRejectedError) as err:
    show(err)


def place_once(body: Dict[str, Any]) -> Any:
    """A write that may or may not have happened: the same key again is safe, a new key could place it twice."""
    key = str(uuid.uuid4())
    for attempt in range(1, 4):
        try:
            return client.orders.create(account["id"], body, idempotency_key=key)
        except APITimeoutError:
            if attempt == 3:
                raise  # still unknown after the SDK's own retries and ours: read the orders before anything else
        except RateLimitError as err:
            if attempt == 3 or err.retry_after is None:
                raise
            time.sleep(err.retry_after)
    raise RuntimeError("unreachable")
```

```go
package main

import (
	"context"
	"crypto/rand"
	"errors"
	"fmt"
	"log"
	"time"

	phoenixperps "github.com/phoenixperps/sdk/go"
)

func show(err error) {
	var e *phoenixperps.Error
	if !errors.As(err, &e) {
		log.Fatal(err)
	}
	fmt.Printf("%s: %s (HTTP %d, %s) %s\n", e.Kind, e.Code, e.Status, e.RequestID, e.Message)
	if len(e.Details) > 0 {
		fmt.Printf("  details: %s\n", e.Details)
	}
	fmt.Printf("  retryable: %v, more: %s\n", e.Retryable, e.DocURL) // retryable: the same call may succeed later
}

func main() {
	ctx := context.Background()
	client, err := phoenixperps.NewClient()
	if err != nil {
		log.Fatal(err)
	}
	accounts, err := client.Accounts.List(ctx)
	if err != nil {
		log.Fatal(err)
	}
	account := accounts.Data[0].ID

	if _, err := client.Orders.Get(ctx, account, "ord_does_not_exist"); errors.Is(err, phoenixperps.ErrNotFound) {
		show(err)
	} else if err != nil {
		log.Fatal(err)
	}

	_, err = client.Orders.Preview(ctx, account, phoenixperps.CreateOrder{
		Market: "BTC-USD", Side: phoenixperps.OrderSideBuy, Type: phoenixperps.CreateOrderTypeMarket, Size: phoenixperps.Dec("0.0000001"),
	})
	if errors.Is(err, phoenixperps.ErrValidation) || errors.Is(err, phoenixperps.ErrRuleRejected) {
		show(err)
	} else if err != nil {
		log.Fatal(err)
	}
}

// placeOnce places an order whose outcome may stay unknown: the same key again is safe, a new key could place it twice.
// ErrTimeout is the SDK's own timeout; a call your ctx ended answers ctx.Err() (unknown too: a fresh ctx, the same key).
func placeOnce(ctx context.Context, client *phoenixperps.Client, account string, body phoenixperps.CreateOrder) (*phoenixperps.Order, error) {
	b := make([]byte, 16)
	_, _ = rand.Read(b)
	key := fmt.Sprintf("%x", b)
	for attempt := 1; ; attempt++ {
		order, err := client.Orders.Create(ctx, account, body, phoenixperps.WithIdempotencyKey(key))
		var e *phoenixperps.Error
		switch {
		case err == nil:
			return order, nil
		case attempt < 3 && errors.Is(err, phoenixperps.ErrTimeout):
			continue // still unknown after the SDK's own retries: the same key
		case attempt < 3 && errors.As(err, &e) && e.Kind == phoenixperps.KindRateLimit && e.RetryAfter > 0:
			time.Sleep(e.RetryAfter)
			continue
		default:
			return nil, err
		}
	}
}
```

```csharp
#:package PhoenixPerps.Sdk@1.0.0
using PhoenixPerps;

using var client = new PhoenixPerpsClient();
var account = (await client.Accounts.ListAsync()).Data[0].Id;

try
{
    await client.Orders.GetAsync(account, "ord_does_not_exist");
}
catch (NotFoundException err)
{
    Show(err);
}

try
{
    await client.Orders.PreviewAsync(account, new CreateOrder { Market = "BTC-USD", Side = OrderSide.Buy, Type = CreateOrderType.Market, Size = 0.0000001m });
}
catch (Exception err) when (err is ValidationException or RuleRejectedException)
{
    Show((PhoenixPerpsException)err);
}

static void Show(PhoenixPerpsException err)
{
    Console.WriteLine($"{err.GetType().Name}: {err.Code} (HTTP {err.Status}, {err.RequestId}) {err.Message}");
    if (err.Details is { } details) Console.WriteLine($"  details: {details}");
}

static class Orders
{
    // a write that may or may not have happened: the same key again is safe, a new key could place it twice
    public static async Task<Order> PlaceOnce(PhoenixPerpsClient client, string account, CreateOrder body)
    {
        var options = new RequestOptions { IdempotencyKey = Guid.NewGuid().ToString() };
        for (var attempt = 1; ; attempt++)
        {
            try
            {
                return await client.Orders.CreateAsync(account, body, options);
            }
            catch (ApiTimeoutException) when (attempt < 3)
            {
                // still unknown after the SDK's own retries: the same key
            }
            catch (RateLimitException err) when (attempt < 3 && err.RetryAfter is { } wait)
            {
                await Task.Delay(wait);
            }
        }
    }
}
```

```java
import com.phoenixperpsfunding.sdk.PhoenixPerpsClient;
import com.phoenixperpsfunding.sdk.PhoenixPerpsException;
import com.phoenixperpsfunding.sdk.RequestOptions;
import com.phoenixperpsfunding.sdk.gen.CreateOrder;
import com.phoenixperpsfunding.sdk.gen.CreateOrderType;
import com.phoenixperpsfunding.sdk.gen.Order;
import com.phoenixperpsfunding.sdk.gen.OrderSide;
import java.math.BigDecimal;
import java.util.UUID;

final class Example12 {
    public static void main(String[] args) {
        PhoenixPerpsClient client = PhoenixPerpsClient.fromEnv();
        String account = client.accounts().list().data().get(0).id();

        try {
            client.orders().get(account, "ord_does_not_exist");
        } catch (PhoenixPerpsException.NotFoundException err) {
            show(err);
        }

        try {
            client.orders().preview(account, new CreateOrder().market("BTC-USD").side(OrderSide.BUY).type(CreateOrderType.MARKET).size(new BigDecimal("0.0000001")));
        } catch (PhoenixPerpsException.ValidationException | PhoenixPerpsException.RuleRejectedException err) {
            show(err);
        }
    }

    static void show(PhoenixPerpsException err) {
        System.out.printf("%s: %s (HTTP %s, %s) %s%n", err.getClass().getSimpleName(), err.code(), err.status(), err.requestId(), err.getMessage());
        if (err.details() != null) System.out.printf("  details: %s%n", err.details());
        System.out.printf("  retryable: %s%s%n", err.retryable(), err.docUrl() == null ? "" : ", see " + err.docUrl());
    }

    /** A write that may or may not have happened: the same key again is safe, a new key could place it twice. */
    static Order placeOnce(PhoenixPerpsClient client, String account, CreateOrder body) throws InterruptedException {
        RequestOptions options = RequestOptions.none().withIdempotencyKey(UUID.randomUUID().toString());
        for (int attempt = 1; ; attempt++) {
            try {
                return client.orders().create(account, body, options);
            } catch (PhoenixPerpsException.ApiTimeoutException err) {
                if (attempt >= 3) throw err; // still unknown after the SDK's own retries and ours: read the orders first
            } catch (PhoenixPerpsException.RateLimitException err) {
                if (attempt >= 3 || err.retryAfter() == null) throw err;
                Thread.sleep(err.retryAfter().toMillis());
            }
        }
    }
}
```

```rust
use phoenixperps::{dec, Client, CreateOrder, CreateOrderType, Error, ErrorKind, Order, OrderSide, RequestOptions};

fn show(err: &Error) {
    println!("{:?}: {} (HTTP {:?}, {:?}) {}", err.kind, err.code, err.status, err.request_id, err.message);
    if let Some(details) = &err.details {
        println!("  details: {details}");
    }
}

/// A write that may or may not have happened: the same key again is safe, a new key could place it twice.
pub async fn place_once(client: &Client, account: &str, body: &CreateOrder) -> phoenixperps::Result<Order> {
    let options = RequestOptions { idempotency_key: Some(uuid::Uuid::new_v4().to_string()), ..Default::default() };
    let mut attempt = 1;
    loop {
        match client.orders().create_with(account, body, &options).await {
            Err(err) if attempt < 3 && matches!(err.kind, ErrorKind::Timeout) => {} // still unknown: the same key
            Err(err) if attempt < 3 && matches!(err.kind, ErrorKind::RateLimit) && err.retry_after.is_some() => {
                tokio::time::sleep(err.retry_after.unwrap_or_default()).await;
            }
            done => return done,
        }
        attempt += 1;
    }
}

#[tokio::main]
async fn main() -> phoenixperps::Result<()> {
    let client = Client::from_env()?;
    let account = client.accounts().list().await?.data[0].id.clone();

    match client.orders().get(&account, "ord_does_not_exist").await {
        Err(err) if matches!(err.kind, ErrorKind::NotFound) => show(&err),
        other => {
            other?;
        }
    }

    let tiny = CreateOrder { market: "BTC-USD".into(), side: OrderSide::Buy, r#type: CreateOrderType::Market, size: Some(dec("0.0000001")), ..Default::default() };
    match client.orders().preview(&account, &tiny).await {
        Err(err) if matches!(err.kind, ErrorKind::Validation | ErrorKind::RuleRejected) => show(&err),
        other => {
            other?;
        }
    }
    Ok(())
}
```

```php
<?php
require 'vendor/autoload.php';

use PhoenixPerps\Client;
use PhoenixPerps\Exception\ApiTimeoutException;
use PhoenixPerps\Exception\NotFoundException;
use PhoenixPerps\Exception\PhoenixPerpsException;
use PhoenixPerps\Exception\RateLimitException;
use PhoenixPerps\Exception\RuleRejectedException;
use PhoenixPerps\Exception\ValidationException;
use PhoenixPerps\Model\Order;
use PhoenixPerps\RequestOptions;

$client = new Client();
$account = $client->accounts->list()->data[0]->id;

function show(PhoenixPerpsException $err): void
{
    printf("%s: %s (HTTP %s, %s) %s\n", (new ReflectionClass($err))->getShortName(), $err->errorCode, $err->status, $err->requestId, $err->getMessage());
    if ($err->details !== null) {
        printf("  details: %s\n", json_encode($err->details));
    }
}

try {
    $client->orders->get($account, 'ord_does_not_exist');
} catch (NotFoundException $err) {
    show($err);
}

try {
    $client->orders->preview($account, ['market' => 'BTC-USD', 'side' => 'buy', 'type' => 'market', 'size' => '0.0000001']);
} catch (ValidationException | RuleRejectedException $err) {
    show($err);
}

/** A write that may or may not have happened: the same key again is safe, a new key could place it twice. */
function placeOnce(Client $client, string $account, array $body): Order
{
    $options = new RequestOptions(idempotencyKey: bin2hex(random_bytes(16)));
    for ($attempt = 1; ; $attempt++) {
        try {
            return $client->orders->create($account, $body, $options);
        } catch (ApiTimeoutException $err) {
            if ($attempt >= 3) {
                throw $err; // still unknown after the SDK's own retries and ours: read the orders first
            }
        } catch (RateLimitException $err) {
            if ($attempt >= 3 || $err->retryAfter === null) {
                throw $err;
            }
            usleep((int) ($err->retryAfter * 1_000_000));
        }
    }
}
```
