ホーム 全セッション S04

例外のまま useCase の外へ伝わる障害

13 / 19 目安 1.5分

ページ一覧

解決策(課題2): 保存の障害は、Result に含まれず、例外のまま useCase の外へ伝わります。

課題2の後半です。保存中にデータベースへの接続が切れるような障害では、利用者が次の操作を選べないため、Result に含めず、例外のまま送出(throw)します。

  1. 予約は見つかり、来院済みです。ensureAppointmentFound と ensureCheckedIn は Ok を返します。

  2. 状態遷移で診察中の予約を作り、store.save で保存します。

  3. 保存の途中でデータベースへの接続が切れ、store.save が例外を投げます。

  4. この例外は Result に変換しません。startExamination は値を返さずに終了し、route の match と switch には渡されません。

  5. 例外を最後に受け取る場所(app.onError)が例外を受け取り、500 を返します。

startExamination実線の枠: 例外として伝わる経路

ensureAppointmentFound(
  deps.resolver.resolveById(input.appointmentId),
  input.appointmentId,
)
  .andThen(ensureCheckedIn)
  .map((appointment) =>
    transitionToInExamination(
      appointment,
      input.veterinarianId,
      input.examinationStartedAt,
    ),
  )
  .map((appointment) => {
    deps.store.save(appointment);
    return appointment;
  });
例外が伝わる

例外を最後に受け取る場所(app.onError)→ 500

app.onError((_error, context) => context.text("Internal Server Error", 500));

引用元: examples/session-04-solution/src/useCase/startExamination.ts:29-44 と examples/session-04-solution/src/app.ts:34

route の変更: 修正前は、route の catch が3種類の失敗を受け取りました。修正後の route に catch はありません。業務の失敗は Result として match が受け取り、保存の障害は例外のまま app.onError が受け取って 500 を返します。