Skip to content

Customizing HttpApi Errors (For RFC 9457 Problem Details) #5367

Closed

Description

@tobimori

What is the problem this feature would solve?

As a developer, I want my Public API to have a standardized error format following RFC 9457, that does not use Effect's proprietary _tag for differentiation.

Currently, HttpApi doesn't support Schema.transform and HttpApiDecodeError is hardcoded for every API route (even if it doesn't have any kind of input. #4751)

What is the feature you are proposing to solve the problem?

What alternatives have you considered?

It's possible to solve this by creating some kind of middleware and OpenAPI transform, but this is really ugly and prone to break.

Activity

  1. added
    enhancement
    on Aug 10, 2025
  2. Avaq commented on Sep 4, 2025

    @Avaq
    Contributor

    Hey I found this, and I think it may be a duplicate of my own feature request: #5465

    @tobimori since you closed this, has it been solved?

  3. tobimori commented on Sep 4, 2025

    @tobimori
    ContributorAuthor

    @Avaq

    I used a middleware:

    import { HttpMiddleware, HttpServerResponse } from '@effect/platform'
    import { HttpApiDecodeError } from '@effect/platform/HttpApiError'
    import { Effect, Schema } from 'effect'
    import { ValidationError } from './errors'
    
    /**
     * Transform from HttpApiDecodeError to ValidationError Problem Details format
     */
    const HttpApiDecodeErrorToValidationError = Schema.transform(HttpApiDecodeError, ValidationError, {
    	strict: false,
    	decode: (httpError) => ({
    		type: 'urn:piqy:errors:validation' as const,
    		title: 'Validation Error' as const,
    		status: 400 as const,
    		detail: httpError.message,
    		issues: httpError.issues,
    	}),
    	encode: (validationError) =>
    		new HttpApiDecodeError({
    			message: validationError.detail,
    			// biome-ignore lint/suspicious/noExplicitAny: no idea why
    			issues: validationError.issues as any,
    		}),
    })
    
    /**
     * Middleware that transforms HttpApiDecodeError responses to Problem Details format
     */
    export const ProblemDetailsDecodeErrorMiddleware = HttpMiddleware.make((app) =>
    	Effect.gen(function* () {
    		const response = yield* app
    
    		if (response.body._tag === 'Uint8Array') {
    			const decoder = new TextDecoder()
    			const text = decoder.decode(response.body.body)
    
    			if (text.includes('HttpApiDecodeError')) {
    				const validationError = yield* Schema.decode(HttpApiDecodeErrorToValidationError)(JSON.parse(text)).pipe(
    					Effect.catchTag('ParseError', () => Effect.succeed(response)),
    				)
    
    				return yield* HttpServerResponse.json(validationError, {
    					status: 400,
    					headers: {
    						'content-type': 'application/problem+json',
    					},
    				})
    			}
    		}
    
    		return response
    	}),
    )

    Also, it's a duplicate of #4751, which is the main reason I closed this

  4. Avaq commented on Sep 4, 2025

    @Avaq
    Contributor

    Right, thanks!!

    And yikes 🙈 having to decode the already byte-encoded, ready for flight, response body 😳

    And that's not to mention that you'd also need an additional hack of the OpenAPI specs generated from the underlying HttpApi, because it doesn't know about your middleware.

    I hope a better solution will come along soon!

  5. tobimori commented on Sep 4, 2025

    @tobimori
    ContributorAuthor

    yes, I have a similar thing for my OpenApi. but it's the only way to male it possible right now.

  6. Avaq commented on Sep 8, 2025

    @Avaq
    Contributor

    @tobimori I opened #5479, which may solve part of the problem, if accepted.

    With it, you can just do .addError(HttpApiDecodeErrorToValidationError) and it'll take precedence over the built-in HttpApiDecodeError schema.

    The remaining part of the problem is that the HttpApiDecodeError would still be listed in JsonSchema responses, but in practice it wouldn't actually come out of your API implementation.

  7. linrium commented on Sep 13, 2025

    @linrium

    Do can I use it with HttpBuilderApi. I tried but it didn't work

  8. janstuemmel commented on Sep 17, 2025

    @janstuemmel

    @Avaq

    I used a middleware:

    import { HttpMiddleware, HttpServerResponse } from '@effect/platform'
    import { HttpApiDecodeError } from '@effect/platform/HttpApiError'
    import { Effect, Schema } from 'effect'
    import { ValidationError } from './errors'

    /**

    • Transform from HttpApiDecodeError to ValidationError Problem Details format
      */
      const HttpApiDecodeErrorToValidationError = Schema.transform(HttpApiDecodeError, ValidationError, {
      strict: false,
      decode: (httpError) => ({
      type: 'urn:piqy:errors:validation' as const,
      title: 'Validation Error' as const,
      status: 400 as const,
      detail: httpError.message,
      issues: httpError.issues,
      }),
      encode: (validationError) =>
      new HttpApiDecodeError({
      message: validationError.detail,
      // biome-ignore lint/suspicious/noExplicitAny: no idea why
      issues: validationError.issues as any,
      }),
      })

    /**

    • Middleware that transforms HttpApiDecodeError responses to Problem Details format
      /
      export const ProblemDetailsDecodeErrorMiddleware = HttpMiddleware.make((app) =>
      Effect.gen(function
      () {
      const response = yield* app

      if (response.body._tag === 'Uint8Array') {
      const decoder = new TextDecoder()
      const text = decoder.decode(response.body.body)

         if (text.includes('HttpApiDecodeError')) {
         	const validationError = yield* Schema.decode(HttpApiDecodeErrorToValidationError)(JSON.parse(text)).pipe(
         		Effect.catchTag('ParseError', () => Effect.succeed(response)),
         	)
      
         	return yield* HttpServerResponse.json(validationError, {
         		status: 400,
         		headers: {
         			'content-type': 'application/problem+json',
         		},
         	})
         }
      

      }

      return response
      }),
      )

    Also, it's a duplicate of #4751, which is the main reason I closed this

    Hey @tobimori

    i found a solution to do this a bit prettier

    const errorMiddleware = HttpMiddleware.make((response) =>
    	response.pipe(
    		Effect.catchTags({
    			HttpApiDecodeError: () => HttpServerResponse.empty({ status: 400 }),
    		}),
    	),
    );
    
    const ApiLive = pipe(
    	HttpApiBuilder.api(Api),
    	Layer.provide(HttpApiBuilder.middleware(errorMiddleware)),
    	Layer.provide(AuthenticationLive),
    );

    yan you provide a example on how you did get rid of the error in the open api spec?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions