説明用のコード: 同じ診察開始を safeTry で実装した例import { ok, safeTry, type Result } from "neverthrow";
export const startExamination =
(deps: Dependencies) =>
(input: StartExaminationInput): Result<InExamination, StartExaminationError> =>
safeTry(function* () {
const found = yield* ensureAppointmentFound(
deps.resolver.resolveById(input.appointmentId),
input.appointmentId,
);
const checkedIn = yield* ensureCheckedIn(found);
const next = transitionToInExamination(
checkedIn,
input.veterinarianId,
input.examinationStartedAt,
);
deps.store.save(next);
return ok(next);
}); andThen の連結では、前の工程の成功値を、次の工程へ直接渡します。途中の成功値を後の工程でも使用するときや、名前を付けて上から順に読みたいときは、safeTry でも実装できます。
yield* した Result が Err の場合、その場で safeTry 全体から同じ失敗を返します。Ok の場合、成功値を取り出して次の行へ進みます。
safeTry は Result の失敗を伝える仕組みで、throw された例外を捕捉する try/catch ではありません。保存の障害は、これまでと同じく例外のまま useCase の外へ伝わります。