softwaremill / tapir

Rapid development of self-documenting APIs
https://tapir.softwaremill.com
Apache License 2.0
1.35k stars 411 forks source link

Can we support custom error message for Enumeration Validation? #3825

Open dungdq2002 opened 4 months ago

dungdq2002 commented 4 months ago

Feature request

Since we can validate an Enumeration using sttp.tapir.Validator.Enumeration, I want to have a custom message for the invalid case.

Use case

For example, when we want to validate a list of enumeration inputs, if one of them fails the validation, the error message is too generic to specify which one is wrong.

Proposed solution

We can add an optional field to sttp.tapir.Validator.Enumeration as showMessageOpt: Option[T => String] to handle the error message.

Besides this approach, do we have any workaround? If not, I can help to implement this.

adamw commented 4 months ago

Can you share some more detail as to what kind of messages you are seeing now, and what you'd like to improve?

The error messages can already be customised (although globally) using the DecodeFailureHandler (see https://tapir.softwaremill.com/en/latest/server/errors.html#decode-failures, and https://github.com/softwaremill/tapir/blob/abeb5d72e4e7a16c4da3830a59eb58862dfda69b/server/core/src/main/scala/sttp/tapir/server/interceptor/decodefailure/DecodeFailureHandler.scala#L259 - you can customise the default decode value handler with custom message rendering)

dungdq2002 commented 4 months ago

For example, we have a field pets: List[Pet], and we already define an enum Pet = { Cat, Dog }. If users pass in List(Dog, Lion), the error message is only "pets: Invalid", and I think "pets: Lion invalid" or something like that will be more explainable.

Currently, we implement the schema as: Schema[Pet]: Schema(ValidatorEnum[Pet]), then Schema[pets]: Schema[Pet].asIterable.

adamw commented 3 months ago

@dungdq2002 is that a field in a json body, or a query/path parameter? some more details on your setup would be helpful :)