Created
September 4, 2018 16:36
-
-
Save hoff2/50ba81b676ca63d903b3f276aa7eab1b to your computer and use it in GitHub Desktop.
circe enumeration codec with better error message?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def enumEncoder[A <: Enumeration](a: A): Encoder[a.Value] = | |
Encoder.encodeString.contramap[a.Value](_.toString) | |
def enumDecoder[A <: Enumeration](a: A): Decoder[a.Value] = | |
Decoder.decodeString.emap(s => | |
try { | |
Right(a.withName(s)) | |
} catch { | |
case _: NoSuchElementException => Left(s"Invalid enumeration value, valid values are: ${a.values}") | |
}) | |
implicit val encodeDocumentType: Encoder[DocumentType.Value] = enumEncoder(DocumentType) | |
implicit val decodeDocumentType: Decoder[DocumentType.Value] = enumDecoder(DocumentType) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment