Skip to content

Commit e3b44b6

Browse files
authored
add HttpApiMiddleware.layerSchemaErrorTransform (#1756)
1 parent a00bc4a commit e3b44b6

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

.changeset/quick-lamps-dig.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"effect": patch
3+
---
4+
5+
add HttpApiMiddleware.layerSchemaErrorTransform

packages/effect/src/unstable/httpapi/HttpApiMiddleware.ts

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import * as Effect from "../../Effect.ts"
55
import * as Layer from "../../Layer.ts"
66
import { hasProperty } from "../../Predicate.ts"
7-
import type * as Schema from "../../Schema.ts"
7+
import * as Schema from "../../Schema.ts"
88
import { Scope } from "../../Scope.ts"
99
import * as ServiceMap from "../../ServiceMap.ts"
1010
import type { unhandled } from "../../Types.ts"
@@ -292,6 +292,51 @@ export const Service = <
292292
return self
293293
}
294294

295+
/**
296+
* Implement a middleware Layer that transforms `SchemaError`'s.
297+
*
298+
* ```ts
299+
* import { Effect, Schema } from "effect"
300+
* import { HttpApiMiddleware } from "effect/unstable/httpapi"
301+
*
302+
* export class CustomError extends Schema.TaggedErrorClass<CustomError>()("CustomError", {}) {}
303+
*
304+
* export class ErrorHandler extends HttpApiMiddleware.Service<ErrorHandler>()("api/ErrorHandler", {
305+
* error: CustomError
306+
* }) {}
307+
*
308+
* export const ErrorHandlerLayer = HttpApiMiddleware.layerSchemaErrorTransform(
309+
* ErrorHandler,
310+
* (schemaError) =>
311+
* Effect.log("Got SchemaError", schemaError).pipe(
312+
* Effect.andThen(Effect.fail(new CustomError()))
313+
* )
314+
* )
315+
* ```
316+
*
317+
* @since 4.0.0
318+
* @category SchemaError transform
319+
*/
320+
export const layerSchemaErrorTransform = <Id, E extends Schema.Top, Requires>(
321+
service: ServiceMap.Service<Id, HttpApiMiddleware<never, E, Requires>>,
322+
transform: (
323+
error: Schema.SchemaError,
324+
context: { readonly endpoint: HttpApiEndpoint.AnyWithProps; readonly group: HttpApiGroup.AnyWithProps }
325+
) => Effect.Effect<HttpServerResponse, E["Type"] | Schema.SchemaError, Requires | HttpRouter.Provided>
326+
): Layer.Layer<Id> =>
327+
Layer.succeed(
328+
service,
329+
(httpEffect, options) =>
330+
Effect.catch(
331+
httpEffect,
332+
(e): Effect.Effect<
333+
HttpServerResponse,
334+
unhandled | Schema.SchemaError | E["Type"],
335+
Requires | HttpRouter.Provided
336+
> => Schema.isSchemaError(e) ? transform(e, options) : Effect.fail(e)
337+
)
338+
)
339+
295340
/**
296341
* @since 4.0.0
297342
* @category client

0 commit comments

Comments
 (0)