# Handle dmog's failures in a script

Tell success from failure by the exit status, read the failure object on standard error, and know when output was left behind.

A script that runs dmog needs to know whether it worked, what went wrong if it did not, and whether a failed run left part of its output behind. dmog answers all three on standard error and in its exit status.

## Check the exit status

dmog exits 0 on success and with a non-zero status on failure. The status says what kind of failure it was:

```console
$ dmog translate --from json --to yaml repeated.json > out.yaml; echo $?
{"code":"DUPLICATE_MEMBER","message":"member \"name\" appears twice in one object, and a tree's events hold each key once; --whole reads the document whole","path":".name","output":"none"}
1
```

Status 1 is a problem with the input, 2 with the program or the command line, 3 a failure to write, 5 a limit reached, and 6 a run that was stopped. The [failures reference](https://dmog.tabnas.dev/reference/failures.html) maps every code to its status.

## Read the failure object

Standard error holds one JSON object, and standard output holds only the answer. Keep them apart, and parse standard error when the status is not 0:

```sh
if ! dmog translate --from json --to yaml in.json > out.yaml 2> fail.json; then
  code=$(jq -r .code fail.json)
  echo "dmog failed: $code" >&2
fi
```

`code` is the stable name of the failure. `message` is for a person, and its first word, before a colon, is a finer code where there is one, such as `unknown_name`.

## Know what was written

`output` says whether anything reached standard output before the failure:

- `"none"`: nothing was written, and the output file is empty.
- `"partial"`: some output was written first. What was written ends with a whole record, so the file is a prefix of the full answer.

Delete a partial output, or keep it knowing it is a prefix. dmog never writes half a record that it can hold back. For how it holds one, see [Why dmog streams](https://dmog.tabnas.dev/explanation/streaming.html).

## What to watch for

A failure can carry more fields: `row` and `col` for a place in a program, `path` for a place in the document, and `limit` for the limit that was reached. Read the ones your script needs and ignore the rest, since a field may be added.
