# Error handling

An HTTP error returns `*idealpostcodes.APIError`. A failed connection returns the `net/http` error, wrapped with the method and path. Match them with `errors.AsType` and `errors.Is`.

## APIError

`*APIError` carries the HTTP status, the API error code and the body.

| Field        | Contents                                                       |
| ------------ | -------------------------------------------------------------- |
| `StatusCode` | HTTP status, such as `404`                                     |
| `Code`       | API error code, such as `4040`. `0` when the body carries none |
| `Message`    | API error message, or the HTTP status text                     |
| `Body`       | The response body as received, as `[]byte`                     |

errors.gogo

```go
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"

	idealpostcodes "go.ideal-postcodes.co.uk/sdk"
)

func main() {
	client := idealpostcodes.NewClient("ak_test")
	res, err := client.Postcodes(context.Background(), "BR8 7RV", nil)

	apiErr, isAPIErr := errors.AsType[*idealpostcodes.APIError](err)
	switch {
	case isAPIErr && apiErr.Code == 4040:
		var body struct {
			Suggestions []string `json:"suggestions"`
		}
		_ = json.Unmarshal(apiErr.Body, &body)
		fmt.Println("Postcode not found. Try:", body.Suggestions)
	case isAPIErr:
		fmt.Println(apiErr.StatusCode, apiErr.Code, apiErr.Message)
	case err != nil:
		log.Fatal(err)
	default:
		fmt.Println(len(res.Result), "addresses")
	}
}
```

The [error codes guide](/docs/guides/error-codes.md) lists each code and how to fix it.

## Other errors

| Error                     | When                                                                                                                                                              |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ErrMissingManagementKey` | A key, licensee or configuration operation on a client with no Management Key. Returned before any request is sent. Match it with `errors.Is`                     |
| `*ResponseError`          | A success response whose body is not JSON. It holds `StatusCode`, `Body` and the decoding error, which `errors.Unwrap` returns                                    |
| Anything else             | The HTTP client could not complete the request: DNS, connection, TLS or timeout failure. The `net/http` error is wrapped, so `errors.AsType[*url.Error]` finds it |

## Timeouts and cancellation

A context deadline, a cancelled context and the HTTP client's `Timeout` all return an error that `errors.Is` matches to `context.DeadlineExceeded` or `context.Canceled`.

timeout.gogo

```go
package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	idealpostcodes "go.ideal-postcodes.co.uk/sdk"
)

func main() {
	client := idealpostcodes.NewClient("ak_test")
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()

	_, err := client.Postcodes(ctx, "BR8 7RE", nil)
	if errors.Is(err, context.DeadlineExceeded) {
		fmt.Println("timed out")
	}
}
```

The SDK does not retry. A request that fails on the network may still have reached the API, so retry a billable lookup only where a repeat charge is acceptable.
