finch icon indicating copy to clipboard operation
finch copied to clipboard

Workaround for returning a validation errors details back to browser?

Open dkulichkin opened this issue 5 years ago • 1 comments

Currently validation in Finch is based on predicate functions, causing further a NonValid error to be thrown without a chance to add details to it in order to help people to correct it... https://finagle.github.io/finch/user-guide.html#validation

One might of course throw his own typed exceptions from these boolean preicates but that would be a misusing of the initially supposed way. Is there any more elegant solutions for approaching that? Thanks.

dkulichkin avatar Sep 20 '19 15:09 dkulichkin

Hi @dkulichkin. One approach is to use Cats' Validated. I had opened this awhile back to see about getting it into Finch as operators on Endpoint. This would let you do something like this:

path[String].validate({ str: String => 
  if (str.isEmpty) Validated.invalid(Errors(NonEmptyList.of(Error.NotValid(item, "Empty Strings are not allowed"))))
  else Validated.valied(str)
})

Then returning the errors in the body of the response becomes a matter of formatting it the Exception Encoder. This approach is also nice because you can accumulate errors.

Even though we didn't move forward with that PR, its still possible to have this behavior with an implicit class that wraps Endpoint[A]. Although this does come at the cost of having to include another import when you want to use it.

rpless avatar Sep 20 '19 16:09 rpless