# Errors

Every refused request and every failed session says what went wrong in the same way: the shape and every code.

## REST errors

Every error has this shape, with the HTTP status of the table below:

```json
{"error": {"code": "invalid_parameter", "message": "Unknown parameter 'diarise'.", "param": "diarise", "request_id": "req_bf2fed760ba5437ba0933a57"}}
```

| Field | Meaning |
|---|---|
| `code` | What went wrong. Your code reacts to this one. |
| `message` | One sentence for people: what happened and what to do. It may change. |
| `param` | The field or parameter at fault, or `null`. |
| `request_id` | The request's id, `req_` and 24 hex digits. Every response carries it in its `Request-Id` header too, errors or not: give it to Vatis Tech support when you ask about a request. |

A malformed request (a wrong type, a missing required field) answers the same shape, never another format. Here is how to read it:

```bash
# -i shows the status and the Request-Id header with the body
curl -sS -i -H "Authorization: Bearer $VATIS_KEY" "https://api.eu.vatis.tech/v1/usage?group=week"
```

```javascript
const response = await fetch("https://api.eu.vatis.tech/v1/usage?group=week", {
  headers: { Authorization: `Bearer ${process.env.VATIS_KEY}` },
});
if (!response.ok) {
  const { error } = await response.json();
  // react to error.code; show error.message; keep error.request_id in your log
  console.error(`${response.status} ${error.code} (${error.param}): ${error.message} [${error.request_id}]`);
}
```

```go
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

func main() {
	url := "https://api.eu.vatis.tech/v1/usage?group=week"
	request, err := http.NewRequest("GET", url, nil)
	check(err)
	request.Header.Set("Authorization", "Bearer "+os.Getenv("VATIS_KEY"))
	response, err := http.DefaultClient.Do(request)
	check(err)
	defer response.Body.Close()
	if response.StatusCode >= 400 {
		var answer struct {
			Error struct {
				Code, Message, Param string
				RequestID            string `json:"request_id"`
			}
		}
		check(json.NewDecoder(response.Body).Decode(&answer))
		e := answer.Error
		// react to e.Code; show e.Message; keep e.RequestID in your log
		fmt.Fprintf(os.Stderr, "%d %s (%s): %s [%s]\n",
			response.StatusCode, e.Code, e.Param, e.Message, e.RequestID)
	}
}

// check stops the program on an error.
func check(err error) {
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

```python
import os

import httpx

response = httpx.get(
    "https://api.eu.vatis.tech/v1/usage",
    params={"group": "week"},
    headers={"Authorization": f"Bearer {os.environ['VATIS_KEY']}"},
)
if response.is_error:
    error = response.json()["error"]
    # react to error["code"]; show error["message"]; keep error["request_id"] in your log
    print(f"{response.status_code} {error['code']} ({error['param']}): {error['message']} [{error['request_id']}]")
```

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Errors {
    public static void main(String[] args) throws Exception {
        String url = "https://api.eu.vatis.tech/v1/usage?group=week";
        HttpRequest request = HttpRequest.newBuilder(URI.create(url))
            .header("Authorization", "Bearer " + System.getenv("VATIS_KEY"))
            .build();
        HttpResponse<String> response = HttpClient.newHttpClient()
            .send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() >= 400) {
            String error = response.body();
            // react to its code; show its message; keep its request_id in your log
            System.err.println(response.statusCode() + " " + field(error, "code")
                + " (" + field(error, "param") + "): " + field(error, "message")
                + " [" + field(error, "request_id") + "]");
        }
    }

    // Reads a text field of the JSON: Java has no JSON parser built in,
    // a real program would use a library.
    static String field(String json, String name) {
        String value = "\"" + name + "\":\\s*\"((?:[^\"\\\\]++|\\\\.)*+)\"";
        Matcher match = Pattern.compile(value).matcher(json);
        if (!match.find()) {
            return null;
        }
        Pattern escaped = Pattern.compile("\\\\(u....|.)");
        return escaped.matcher(match.group(1)).replaceAll((escape) -> {
            String code = escape.group(1);
            if (code.equals("n")) {
                return "\n";
            }
            if (code.length() > 1) {
                int number = Integer.parseInt(code.substring(1), 16);
                code = String.valueOf((char) number);
            }
            return Matcher.quoteReplacement(code);
        });
    }
}
```

```csharp
using System.Net.Http.Headers;
using System.Text.Json;

using var http = new HttpClient();
var apiKey = Environment.GetEnvironmentVariable("VATIS_KEY");
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", apiKey);

using var response = await http.GetAsync("https://api.eu.vatis.tech/v1/usage?group=week");
if (!response.IsSuccessStatusCode)
{
    var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
    var error = body.RootElement.GetProperty("error");
    var code = error.GetProperty("code");
    var param = error.GetProperty("param");
    var message = error.GetProperty("message");
    var requestId = error.GetProperty("request_id");
    // react to code; show message; keep requestId in your log
    Console.Error.WriteLine(
        $"{(int)response.StatusCode} {code} ({param}): {message} [{requestId}]");
}
```

### Status codes

| Status | Code | When |
|---|---|---|
| 400 | `invalid_parameter` | An unknown, repeated or unsupported field or query parameter, a value out of range, or fields that do not go together; a bad `Idempotency-Key`; a `url` refused or that failed to download; no enabled webhook, or a bad `webhook_id`; form fields over 1 MB; more speakers than the API takes; subtitles of a transcript without word times; a vocabulary entry that breaks the rules (`entries[3]`, a file's `vocabulary[3]`), or more than 10,000 entries (a file's own: 250); an unknown `vocabulary_id`; a vocabulary on a model or a server that takes none. `param` names the field. |
|  | `missing_parameter` | A required field is missing: `model_id`; both `file` and `url`; `format`; `type`; a webhook's `url`; a vocabulary's `name`. |
|  | `invalid_request` | A body that is not a valid request: not multipart or urlencoded, malformed, a part without a name, more than 200 parts, JSON that is not an object; a 51st webhook. |
|  | `unsupported_model` | A `model_id` your workspace does not have, or a real-time model sent to batch. |
|  | `invalid_audio` | An empty file, no audio that can be decoded, or more than 2 channels with `multichannel`. |
|  | `audio_too_long` | The audio is longer than the API takes (10 hours). |
| 401 | `unauthorized` | No key; a wrong, revoked or expired key; a used, expired or wrong-type token. |
| 403 | `admin_only` | A request that takes an Admin key, made with a Member key ([Authentication and API keys](https://platform.vatis.tech/docs/authentication)); a Member key's `key_id` for another key on `GET /v1/activity`. |
|  | `account_paused` | A new batch job of a paused workspace: its credit is used up, it is over its spend limit, or Vatis Tech paused it ([Limits and free credit](https://platform.vatis.tech/docs/limits)). |
| 404 | `not_found` | An unknown, deleted or expired transcript, webhook, key or vocabulary; another key's transcript, to a Member key; an unknown path. |
| 405 | `invalid_request` | A method the path does not take. The `Allow` header lists the right ones. |
| 409 | `idempotency_conflict` | An `Idempotency-Key` used before for another request. |
|  | `not_completed` | An export of a transcript that is still `queued` or `processing`, or `failed`. |
|  | `last_admin` | Revoking the last active Admin key, or making it a Member. |
|  | `name_taken` | A new key with the name of an active key; a vocabulary with the name of another one. |
|  | `vocabulary_limit` | A 101st saved vocabulary: delete one first. |
|  | `key_revoked` | A change to a revoked key. |
| 413 | `request_too_large` | A file or download over 2 GiB, a request body over 2 GiB and 2 MB, or a JSON body over 64 KB (a vocabulary's: over 8 MB). |
| 429 | `busy` | Too many files wait to be transcribed. Try again after the seconds of the `Retry-After` header. |
| 500 | `internal_error` | Something failed on our side. Try again, and give the `request_id` to support if it stays. |
| 503 | `unavailable` | A service the request needs is not ready. Try again after the seconds of the `Retry-After` header. |

### When a transcription fails

A batch request is answered at once, so a transcription that fails after the API took the request does not answer with an error: the transcript you poll, and the webhook delivery, show `status` `failed` with its `error`, in the same shape (for example `invalid_audio` or `internal_error`; [The transcript object](https://platform.vatis.tech/docs/transcript-object)).

`429` `concurrent_limit` is reserved: it is not sent today.

### Refused before the upload ends

Some refusals are decided on the request's headers, while your client is still sending the file: a `401`, or a `413` by the declared length. Nothing of the file is kept.

- A client that reads while it sends gets that status at once.
- Another gets it when it stops sending: at the end of the file, or when the server closes the connection, about 30 s after the refusal.
- The connection ends after such an answer, even when its `Connection` header says `keep-alive`.

## Session errors

A live session that fails gets one `error` message, then the server closes the connection. Every refusal comes after the WebSocket opened, so a web page can read the reason too:

```json
{"type": "error", "code": "invalid_parameter", "message": "diarise: unknown parameter", "param": "diarise"}
```

| Code | When | Close code |
|---|---|---|
| `unauthorized` | No key or token, or one that is not valid: a wrong, revoked or expired key; a used, expired or wrong-type token. | 1008 |
| `invalid_parameter` | A query parameter that is unknown, empty, not supported or out of range (`param` names it), one sent without the one it needs (`speaker_updates` without `diarize=true`, `turn_sensitivity` without `commit=turn`), `commit=turn` with a model that is not Romanian, a `vocabulary_id` that names no vocabulary of your workspace, a `vocabulary` message with a bad entry (`param` `entries[3]`), or a text message the server does not know (`param` `type`). | 1008 |
| `audio_chunk_too_large` | A frame of more than 1 s of audio. | 1009 |
| `capacity` | Every live session your workspace may have open is in use (a two-channel session needs 2), or there is no free capacity for a new session. The message says which, for example "This account can run 10 real-time sessions at a time: try again when one ends." | 1013 |
| `account_paused` | A paused workspace: its credit is used up, it is over its spend limit, or Vatis Tech paused it. Refused before `session.started`; an open session ends with it about a minute after the pause, after its last `final` messages. The message says which. | 1013 |
| `idle_timeout` | 15 s without any message or audio. | 1008 |
| `session_time_limit` | The session reached the longest a session runs: 4 hours. Its last finals come first. Open a new session to go on. | 1008 |
| `transcriber_error` | The speech service failed, was not available at the start, or did not finish within 30 s of your `end`. | 1011, or 1012 when the service stopped for an update |
| `internal_error` | Something failed on our side, or the saved vocabulary of `vocabulary_id` cannot be read for a moment: connect again in a few seconds. | 1011 |
| `service_restart` | The service restarts, for an update. The `final` messages of all the audio it received come first. `resume_s` is the second of the session's audio to send again from ([Real-time transcription](https://platform.vatis.tech/docs/realtime)). | 1012 |

- Refused before `session.started`: `unauthorized`, `invalid_parameter`, `capacity`, `account_paused`, `transcriber_error` (no speech service free), `internal_error` (a saved vocabulary that cannot be read for a moment) and `service_restart`.
- `speaker_updates` without `diarize=true` is refused: `{"type": "error", "code": "invalid_parameter", "message": "speaker_updates: needs diarize=true", "param": "speaker_updates"}`, close code 1008.
- `turn_sensitivity` without `commit=turn` is refused the same way: `{"type": "error", "code": "invalid_parameter", "message": "turn_sensitivity: needs commit=turn", "param": "turn_sensitivity"}`. End of turn is for Romanian models only: `commit=turn` with another model gets `invalid_parameter` with `param` `commit` ([End of turn](https://platform.vatis.tech/docs/realtime/end-of-turn)).
- `invalid_audio` is reserved: raw audio cannot be invalid, so it is not sent today.
- Speakers lost in the middle of a session do not end it: later words have `"speaker": null`.

### Close codes

| Close code | Means | What to do |
|---|---|---|
| 1000 | A normal end, after your `end` and `session.ended`. | Nothing. |
| 1006 | The connection dropped without a close (a network failure). A connection that never opened (a wrong host or path) shows the same in a browser. | Connect again, and go on from the end of the last final. |
| 1008 | A refusal or a client error: the error's code says which. | Fix the cause before you connect again. |
| 1009 | A frame or message too large. | Send smaller frames: 100 ms of audio is best. |
| 1011 | A failure on our side. | Connect again, and go on from the end of the last final. |
| 1012 | The service restarts. | Connect again at once, and send the audio again from `resume_s`. |
| 1013 | No session free now, or a paused workspace. | Try again later. A paused workspace needs credit first. |

## Strict parameters

A parameter the API does not know, or does not support, is refused, never ignored, so a result never silently lacks what you asked for. A misspelled `diarise` is refused rather than giving a transcript without speakers.

- A REST request answers `400` `invalid_parameter`, with `param` naming it.
- A live session gets an `error` message naming it, then closes with 1008.
- The same holds for any query parameter an endpoint does not take, even with an empty value.
- A field sent twice is refused on `POST /v1/speech-to-text` and on an export. In any other query, the last value counts.

An empty value (`name=`) depends on where it is sent:

| Where | An empty value |
|---|---|
| A form field of `POST /v1/speech-to-text`; the query of an export, of usage or of activity; `after` and `status` of `GET /v1/transcripts`; `token` | Counts as not sent, so a required one is `400` `missing_parameter`. |
| `limit` of `GET /v1/transcripts` | Is refused: `400` `invalid_parameter`. |
| The query of a live session, `token` apart | Is refused: `invalid_parameter`, message `<name>: empty`, close code 1008. |

## What to retry

| You get | Retry? |
|---|---|
| `429` `busy`, `503` `unavailable` | Yes, after the seconds of the `Retry-After` header. To repeat a batch request safely, send it with the same `Idempotency-Key` ([Batch transcription](https://platform.vatis.tech/docs/batch)). |
| `500` `internal_error` | Yes, a few times, waiting longer each time. If it stays, give the request_id to support. |
| Close 1006, 1011, 1012 | Yes, at once and then after a growing wait, going on where the last `final` ended (from `resume_s` after 1012). |
| `capacity`, or `transcriber_error` before `session.started` | Yes, for a while: a session ends, or the service is back. |
| `account_paused` | Not until the cause is gone: the message says it. Add credit when it is used up; wait a few minutes after the spend limit ([Limits and free credit](https://platform.vatis.tech/docs/limits)). |
| `400`, `401`, `403`, `404`, `409`, `413`; close 1008, 1009 | No: the same request gets the same answer. Fix it first. |

> **Ignore what you do not know.** New fields, message types and codes may be added inside `/v1`. Ignore fields and messages you do not know, and treat an unknown code by its HTTP status or close code.

## Next steps

- [Limits and free credit](https://platform.vatis.tech/docs/limits): the limit behind each refusal.
- [Real-time transcription](https://platform.vatis.tech/docs/realtime): every message of a live session, and how to go on after a restart.
- [All endpoints](https://platform.vatis.tech/docs/endpoints): every request the API takes.
