Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle unexpected discriminator values #1022

Open
karayusuf opened this issue May 5, 2023 · 2 comments
Open

Handle unexpected discriminator values #1022

karayusuf opened this issue May 5, 2023 · 2 comments
Labels

Comments

@karayusuf
Copy link

karayusuf commented May 5, 2023

Is there a way to decode unexpected discriminator types? Right now, an exception is raised when an unknown discriminator value is provided. I'd like to be able to deserialize the unknown type into an object rather than handling the error.

Example config

object Schema {
  sealed trait Event {
    def kind
  }

  case class CreateEvent() extends Event
  case class DeleteEvent() extends Event
  case class UnknownEvent(kind: String)

  implicit val codec = JsonCodecMaker.make[Event](CodecMakerConfig
        .withDiscriminatorFieldName(Some("kind"))
        // Totally made up config method to show the desired behavior.
        // Not trying to suggest an exact implementation.
        .withDiscriminatorFallback(UnknownEvent())) 
}

Example usage

When an unexpected value is returned, return the configured unknown event class.

val event = readFromString[Schema.Event]("""
  { 
    "kind": "asdfasdf",
    "ranom": "field"
  }
""")

event shouldBe a[Schema.UnknownEvent]
event.kind should equal("asdfasdf")
@plokhotnyuk
Copy link
Owner

@karayusuf Hi, Joe!

If I understand correctly your JSON input cannot be fully modeled by case classes or evolves faster than your model and the idea of your solution is to avoid throwing of an error for events that are not modeled yet.

Based on your code samples I wrote the possible solution here.

Please check if my solution works for your case.

@karayusuf
Copy link
Author

Hi @plokhotnyuk . The code sample you provided looks fantastic. Will play around with it today. Thanks so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants