|
| 1 | +import { Provider } from "@/provider/provider" |
| 2 | +import { Session } from "@/session/session" |
| 3 | +import { NotFoundError } from "@/storage/storage" |
| 4 | +import { iife } from "@/util/iife" |
| 5 | +import { NamedError } from "@opencode-ai/core/util/error" |
| 6 | +import * as Log from "@opencode-ai/core/util/log" |
| 7 | +import { Cause, Effect } from "effect" |
| 8 | +import { HttpRouter, HttpServerError, HttpServerResponse } from "effect/unstable/http" |
| 9 | + |
| 10 | +const log = Log.create({ service: "server" }) |
| 11 | + |
| 12 | +// Keep typed HttpApi failures on their declared error path; this boundary only replaces defect-only empty 500s. |
| 13 | +export const errorLayer = HttpRouter.middleware<{ handles: unknown }>()((effect) => |
| 14 | + effect.pipe( |
| 15 | + Effect.catchCauseIf( |
| 16 | + (cause) => Cause.hasDies(cause), |
| 17 | + (cause) => { |
| 18 | + const error = Cause.squash(cause) |
| 19 | + if (HttpServerResponse.isHttpServerResponse(error)) return Effect.succeed(error) |
| 20 | + if (HttpServerError.isHttpServerError(error)) |
| 21 | + return HttpServerError.causeResponse(cause).pipe(Effect.map((response) => response[0])) |
| 22 | + |
| 23 | + log.error("failed", { error, cause: Cause.pretty(cause) }) |
| 24 | + |
| 25 | + if (error instanceof NamedError) { |
| 26 | + return Effect.succeed( |
| 27 | + HttpServerResponse.jsonUnsafe(error.toObject(), { |
| 28 | + status: iife(() => { |
| 29 | + if (error instanceof NotFoundError) return 404 |
| 30 | + if (error instanceof Provider.ModelNotFoundError) return 400 |
| 31 | + if (error.name === "ProviderAuthValidationFailed") return 400 |
| 32 | + if (error.name.startsWith("Worktree")) return 400 |
| 33 | + return 500 |
| 34 | + }), |
| 35 | + }), |
| 36 | + ) |
| 37 | + } |
| 38 | + if (error instanceof Session.BusyError) { |
| 39 | + return Effect.succeed( |
| 40 | + HttpServerResponse.jsonUnsafe(new NamedError.Unknown({ message: error.message }).toObject(), { |
| 41 | + status: 400, |
| 42 | + }), |
| 43 | + ) |
| 44 | + } |
| 45 | + |
| 46 | + return Effect.succeed( |
| 47 | + HttpServerResponse.jsonUnsafe( |
| 48 | + new NamedError.Unknown({ |
| 49 | + message: error instanceof Error && error.stack ? error.stack : String(error), |
| 50 | + }).toObject(), |
| 51 | + { status: 500 }, |
| 52 | + ), |
| 53 | + ) |
| 54 | + }, |
| 55 | + ), |
| 56 | + ), |
| 57 | +).layer |
0 commit comments