Reusing common errorOutVariants

Is there a way I can define errorOutVariants in a single place that can be reused on multiple endpoints?

So I have for all my endpoints some kind of authorization error variant, bad requests, server errors that are in all of the endpoints. I also have a specific error out variant for each endpoints.

So I would like to be able to do something like this:


val commonVariants = List(oneOfVariant(BadRequestVariant),
    oneOfVariant(AuthorizationErrorVariant),
    oneOfDefaultVariant(DefaultErrorVariant))

securedEndpoint.get
.blahblahblah
.errorOutVariants(
   oneOfVariant(statusCode(StatusCode.NotFound).and(jsonBody[NotFound]))
)
.errorOutVariants(commonVariants)

Potentially even better is when I define my PartialServerEndpoint for authentication, since all my endpoints use that, be able to define that there.

I had tried making it so that securedEndpoint.errorOutVariants() had all my common error outs, but I got runtime errors about them not being defined when I called the endpoint.

I don’t think you can define variants in a List in a way that you can reuse them later. However, putting them directly in a base securedEndpoint should be good enough, you do it once anyway, right?
Something like:

val securedEndpoint = 
endpoint
  // here go your base auth & header inputs
      .errorOut(
        oneOf(
          oneOfVariant(statusCode(StatusCode.BadRequest).and(jsonBody[BadRequestError])),
          oneOfVariant(
            statusCode(StatusCode.Unauthorized).and(emptyOutputAs(UnauthorizedErr))
          ),
          oneOfDefaultVariant(statusCode(StatusCode.InternalServerError).and(jsonBody[DefaultError]))
        )
      )

Now you can define a specialized endpoint:

securedEndpoint
.get
.blahblah
.errorOutVariant(oneOfVariant(statusCode(StatusCode.NotFound).and(jsonBody[NotFound])))

The documentation mentions reusing error variants here: One-of variants — tapir 1.x documentation

Hey that works. I had been using the errorOutVariant in the securedendpoint and the server kept throwing errors. Thanks!

1 Like