this post was submitted on 23 Jan 2024
364 points (96.7% liked)
Fediverse
28281 readers
668 users here now
A community to talk about the Fediverse and all it's related services using ActivityPub (Mastodon, Lemmy, KBin, etc).
If you wanted to get help with moderating your own community then head over to !moderators@lemmy.world!
Rules
- Posts must be on topic.
- Be respectful of others.
- Cite the sources used for graphs and other statistics.
- Follow the general Lemmy.world rules.
Learn more at these websites: Join The Fediverse Wiki, Fediverse.info, Wikipedia Page, The Federation Info (Stats), FediDB (Stats), Sub Rehab (Reddit Migration), Search Lemmy
founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
You can bubble up the Error with
?
operator. It just has to be explicit (function that wants to use?
must return Result) so that the code up the stack is aware that it will receive Result which might be Err. The function also has defined Error type, so you know exactly which errors you might receive. (So you're not surprised by unexpected exception type from somewhere deep in the call stack. Not sure about Java, but in Python that is quite a pain)Edit: To provide an example for the mentioned db fetch. Typically your query function would return
Result(Option)
. (SoErr
if there was error,Ok(None)
if there was no error, but query returned no results andOk(Some(results))
if there were results) This is pretty nice to work with, because you can distinguish between "error" and "no resurts" if you want, but you can also decide to handle these same way with:So I have the option to handle the error if it's something I can handle and then the error handling isn't standing in my way. There are no try-catch blocks, I just declare what to (not) do with the error. Or I can decide it's better handled up the stack:
This would be similar to exception bubbling up, but my function has to explicitly return Result and you can see in the code where the "exception" is bubbled up rather than bubbling up due to absence of any handler. In terms predictability I personally find this more predictable.
But like, what kind of error are you gonna handle that's coming from the DB, if it's something like a connection error because the DB is down, then you are shit out of luck you can't handle that anyway, and you probably shouldn't, not from the layer you are calling your DB from, that's a higher level logic, so bubbling Errors there make sense.
and if it's an "error" like findById doesn't always return something, that's what the Optional pattern is for.
what you have described to me seems like a worse version of the checked/unchecked exception system.
I could return 500 (getting
Error
) instead of 404 (gettingNone
) or 200 (gettingSome(results)
) from my web app.Or DB just timed out. The code that did the query is very likely the only code that can reasonably decide to retry for example.