3 ms·
Parsing JSON can produce a finite set of errors that you know about. Such errors are either lexer/parser errors (invalid token encountered, expecting a string a
by bad_user 11y ago
Parsing JSON can produce a finite set of errors that you know about. Such errors are either lexer/parser errors (invalid token encountered, expecting a string and getting something else) or format errors (expecting a DateTime inside a string). One possible type that could express this, copied from Play's JSON, would be this one:
sealed trait JsResult[+A]
case class JsError(errors: Seq[(JsPath, Seq[ValidationError])])
extends JsResult[Nothing]
case class JsSuccess[+A](value: A, path: JsPath)
extends JsResult[A]
So instead of throwing exceptions, you return a JsResult that could represent one or multiple errors.
> So its up to the API consumer, not the producer to decide whether a situation is "truly exceptional" or not.
We kind of agree on this one, as long as we are talking about things the producer can control of course. The producer obviously can't guard well against a hard-disk getting full (and that would be truly exceptional). But for things it can control, the producer shouldn't throw exceptions on JSON parsing, when it could return a JsResult and leave the consumer to decide what to do with it. And the advantage is that JsError is explicit, its shape is explicit, so the consumer knows exactly what happened and it can return a human-readable error message, or it can fall-back to something else, etc.
And then, if you read from a file generated by your software and you expect a valid JSON and it's not what you expect, then that's obviously a bug, which is also an exceptional situation, so exceptions are OK. But that's no longer user input, as you've said.
- azernik 11y agoAbsolutely agree. I think the Play JSON libraries are a good example of leaving that distinction to the user: you can either do jsonValue.as[SomeParsedType] when you want an exception, or jsonValue.validate[SomeParsedType] if you want to keep JsErrors in the normal flow of control. The language makes it very clear. (I tend to use .as() in practice, but in part that's because in the Try[X]/Future[X]/Either[T, X]/etc. monads exceptions work a lot like early returns, which is a nicely-bounded deviation from structured programming that I'm pretty okay with).