# Stopping a journey when its log fails

## What you want to do

The shop's log now writes each line to a logging service, over the network, and a write can fail. You want to know what happens to a journey whose log can't take a line, so that no order goes on with no record of what it did.

## The code

The shop is [chapter 26](https://itinera-dev.org/book/typescript/26-running-async-journeys-while-others-wait.md)'s, with its log changed. The log turns each event into a line, as before, and hands it to the logging service, which answers over the network, so `report` is now `async` and awaits it. The faked service can't take the line saying that the charge of order A-15 succeeded, and throws `LoggingDown`. The log doesn't catch it, so the promise `report` returns rejects with it:

TypeScript, from the program [`ch31_stopping_a_journey_when_its_log_fails`](https://github.com/itinera-dev/book/blob/main/typescript/examples/ch31_stopping_a_journey_when_its_log_fails.ts)

```typescript
/** The logging service's error: it can't take a line. */
class LoggingDown extends Error {
  constructor() {
    super("the logging service is down");
  }
}

/**
 * The shop's logging service, faked: it prints each line it takes, once the
 * network has answered. It is down when the line saying that order A-15's
 * charge succeeded reaches it.
 */
class LoggingService {
  async write(line: string): Promise<void> {
    await network();
    if (line.includes(" A-15 ") && line.endsWith(" step_succeeded charge")) {
      throw new LoggingDown();
    }
    console.log(line);
  }
}

/**
 * The shop's log: it writes a line for every event of a journey to the
 * logging service, starting with the workflow's name and the journey's ID. A
 * line the service refuses fails the report.
 */
class Log implements Reporter {
  private readonly service = new LoggingService();

  async report(event: Event): Promise<void> {
    const said = detail(event);
    const line = `log ${event.workflow} ${event.journeyId} #${String(event.sequence)} ${event.kind}`;
    await this.service.write(said === undefined ? line : `${line} ${said}`);
  }
}
```

`network` is [chapter 26](https://itinera-dev.org/book/typescript/26-running-async-journeys-while-others-wait.md)'s, and `detail` is the function [chapter 12](https://itinera-dev.org/book/typescript/12-trying-again.md) shows, with the cases later chapters added to it, the last in [chapter 22](https://itinera-dev.org/book/typescript/22-finishing-a-journey-early.md). The workflow still lists the log and the desk among its reporters, as [chapter 23](https://itinera-dev.org/book/typescript/23-undoing-a-charge-when-the-shipping-fails.md) shows: a reporter's `report` may return nothing or a promise of nothing, and the executor waits for whichever it gets, as it does for a step's `run`. The desk is [chapter 11](https://itinera-dev.org/book/typescript/11-naming-a-journey.md)'s.

`whatWentWrong`, from [chapter 25](https://itinera-dev.org/book/typescript/25-reading-the-result.md), now also names the error of a reporter that failed:

TypeScript, from the program [`ch31_stopping_a_journey_when_its_log_fails`](https://github.com/itinera-dev/book/blob/main/typescript/examples/ch31_stopping_a_journey_when_its_log_fails.ts)

```typescript
/**
 * The reason of an abort, with the key that was missing or the reporter's
 * error when that is what happened.
 */
function whatWentWrong(abort: Abort): string {
  if (
    abort.reason === "required data missing" &&
    abort.missing.kind === "key"
  ) {
    return `${abort.reason}: ${abort.missing.key}`;
  }
  if (abort.reason === "reporter failed") {
    return `${abort.reason}: ${abort.errorMessage}`;
  }
  return abort.reason;
}
```

The program runs two orders one after the other, with `shop` and `executor` made as [chapter 24](https://itinera-dev.org/book/typescript/24-running-many-journeys.md) makes them, and hands each result to [chapter 25](https://itinera-dev.org/book/typescript/25-reading-the-result.md)'s `followUp`: Ann's, and the order of a new customer, Pat, who pays 50 for a parcel of 3 kg:

TypeScript, from the program [`ch31_stopping_a_journey_when_its_log_fails`](https://github.com/itinera-dev/book/blob/main/typescript/examples/ch31_stopping_a_journey_when_its_log_fails.ts)

```typescript
// The order, the customer, the price, the discount when there is one, the
// parcel, the card, and whether the order is a gift card.
const orders = [
  {
    order: "A-1",
    customer: "Ann",
    price: 40,
    discount: 10,
    parcel: { weight: 2, size: [30, 20, 10] },
    card: "ann-2028",
    giftCard: false,
  },
  {
    order: "A-15",
    customer: "Pat",
    price: 50,
    parcel: { weight: 3, size: [40, 30, 20] },
    card: "pat-2028",
    giftCard: false,
  },
];
for (const order of orders) {
  console.log(`${order.customer}'s order:`);
  followUp(await executor.run(shop.instance(order)));
}
```

It prints:

What `ch31_stopping_a_journey_when_its_log_fails` prints, recorded in [`ch31_stopping_a_journey_when_its_log_fails.txt`](https://github.com/itinera-dev/book/blob/main/typescript/expected/ch31_stopping_a_journey_when_its_log_fails.txt)

```text
Ann's order:
log orders A-1 #1 journey_started order, customer, price, discount, parcel, card, giftCard
log orders A-1 #2 attempt_started lookup, attempt 1
log orders A-1 #3 service_provided lookup gets orderBook from ledger, a Ledger
the order book has no order A-1 yet
log orders A-1 #4 step_succeeded lookup
log orders A-1 #5 contribution_committed completed
log orders A-1 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-1 #7 attempt_started price, attempt 1
log orders A-1 #8 step_succeeded price
log orders A-1 #9 contribution_committed amount
log orders A-1 #10 attempt_started charge, attempt 1
log orders A-1 #11 service_provided charge gets payments from bank, a Bank
the bank charges 30 for order A-1
log orders A-1 #12 step_succeeded charge
log orders A-1 #13 contribution_committed receipt
log orders A-1 #14 hook_called audit: on step success of charge
log orders A-1 #15 contribution_committed audit
log orders A-1 #16 attempt_started ship, attempt 1
log orders A-1 #17 input_adapter_supplied ship gets weight from parcels
log orders A-1 #18 service_provided ship gets carrier from carriers, a MainCarrier
the main carrier books order A-1
log orders A-1 #19 step_info ship: the parcel leaves with receipt R-A-1
log orders A-1 #20 step_succeeded ship
log orders A-1 #21 contribution_committed tracking
log orders A-1 #22 optional_input_absent code
email to Ann: Order A-1 is on its way, tracking T-A-1.
log orders A-1 #23 hook_called notify: on workflow success
log orders A-1 #24 journey_succeeded
the journey succeeded, with receipt R-A-1 and tracking T-A-1
audit: charge took 30, receipt R-A-1
Pat's order:
log orders A-15 #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-15 #2 attempt_started lookup, attempt 1
log orders A-15 #3 service_provided lookup gets orderBook from ledger, a Ledger
the order book has no order A-15 yet
log orders A-15 #4 step_succeeded lookup
log orders A-15 #5 contribution_committed completed
log orders A-15 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-15 #7 attempt_started price, attempt 1
log orders A-15 #8 optional_input_absent discount
log orders A-15 #9 step_succeeded price
log orders A-15 #10 contribution_committed amount
log orders A-15 #11 attempt_started charge, attempt 1
log orders A-15 #12 service_provided charge gets payments from bank, a Bank
the bank charges 50 for order A-15
the journey was aborted (reporter failed: the logging service is down)
```

## How it works

1. **A reporter that fails aborts the journey.** The log's `report` rejected on Pat's `step_succeeded`, so the executor aborted the journey, with the reason `reporter failed`. A throw from a reporter, or a promise it returns that rejects, is the same failure. A reporter can't report an error and carry on, and a journey with no record of what it did is not one the shop can trust, so it doesn't go on.
2. **The abort is recorded at once.** Nothing after it runs: the shipping never starts, so no carrier books Pat's parcel, and no workflow hook runs, so Pat is not told, as [chapter 25](https://itinera-dev.org/book/typescript/25-reading-the-result.md) showed of an aborted journey.
3. **What the journey did stays done.** The bank took Pat's 50 before the abort. No hook of `failedShipping`, as [chapter 26](https://itinera-dev.org/book/typescript/26-running-async-journeys-while-others-wait.md) shows it, is called, since no shipping was given up, so nothing gives the money back. An abort is a fault to fix, as [chapter 25](https://itinera-dev.org/book/typescript/25-reading-the-result.md) said: here, the shop finds Pat's payment with the bank, and refunds it before running the order again, since a new journey would charge Pat again.
4. **The abort carries the reporter's error.** Once `whatWentWrong` has compared `abort.reason` with `reporter failed`, TypeScript lets it read `abort.errorMessage`, the message of what the log threw, which is how it prints the service's own words. `abort.error` holds what was thrown itself, the `LoggingDown`, for code that needs more than its message.
5. **Reporters should be written so that they never fail.** A reporter's failure costs the whole journey, at whatever point it happens. A log that can lose its service should keep its lines, and send them once the service is back, rather than let the error out.

Pat's journey stopped before it did anything it couldn't record. But no record holds Pat's last two events, the charge's success and the abort: the log was the only reporter that printed events, and it was the one that failed.

## Outcomes

We have shown how a journey is aborted when one of its reporters fails, and what it leaves behind.

| The usual way                                                                            | With Itinera                                                                                                |
| ---------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| A log call that fails is often ignored, or crashes the request at whatever line made it. | A reporter that fails aborts the journey with `reporter failed`, at once, and the result carries its error. |
| What a request did before it crashed is often found only by reading the code that ran.   | The events before the abort say what the journey did, up to the charge, and the shipping never started.     |
