# Stream errors

> Preserve stream framing, provider, and terminal-result failures through StreamReader.

- Path: `Guides > Inference > Errors and Cancellation > Stream errors`
- Human: https://looprig.com/docs/guides/inference/errors-and-cancellation/stream-errors
- Machine index: https://looprig.com/llms.txt

Streams have two failure phases: establishment, returned from `Client.Stream`,
and consumption, returned by `StreamReader.Next`.

## Reader

`StreamReader` returns `StreamReaderError` for a nil reader, missing `Next`, or
invalid framing adapter. A non-EOF error from the underlying reader moves it
to a failed terminal state after draining what was already decoded: chunks
buffered from an earlier frame, or returned alongside the error itself, are
delivered first, and every later `Next` then returns that same latched error
without reading another frame. A `StreamResultError` means the codec's
terminal-metadata producer itself failed, so the stream did not reach clean EOF
and `Result` is unavailable. Terminal usage is not validated.

```go
chunk, err := reader.Next()
if err != nil && !errors.Is(err, io.EOF) {
	var resultErr *stream.StreamResultError
	if errors.As(err, &resultErr) {
		// Terminal metadata was not authorized.
	}
	return err
}
_ = chunk
```

## Provider

After a successful HTTP status, a dialect may emit `StreamAPIError` from an
in-stream error event. It is terminal and is not converted into a clean result.
Malformed or unknown events are skipped only where that codec documents
tolerant event decoding; a missing terminal marker leaves `Result` unavailable.

## Source and proof

- [`stream/result.go`](https://github.com/looprig/inference/blob/v0.12.0/stream/result.go)
- [`stream/stream.go`](https://github.com/looprig/inference/blob/v0.12.0/stream/stream.go)
- [`openairesponses/errors.go`](https://github.com/looprig/inference/blob/v0.12.0/codec/openairesponses/errors.go)
- [`anthropicapi/stream.go`](https://github.com/looprig/inference/blob/v0.12.0/codec/anthropicapi/stream.go)

Run `go test ./stream ./codec/...`.
