question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Provide a way to chain Err to Exception

See original GitHub issue

Hi,

Thanks for a cool library. I’ve tried to find a solid way to manage error cases in Python like Rust and found this elegant library.

We’re migrating some of our APIs using result and miss a feature to cover some common patterns we’ve found. As our library clients may not want to change their code base to be aware of result.Ok or result.Err (I hope so in the future though), we’ve decided to change our internal APIs only as a initial step.

So basically we have some of similar codes like

# Internal API
def _get_user() -> Result[User, str]:
    ...

def _raise(e):
    raise e

# Public API
def get_user():
    return _get_user().map_err(lambda e: _raise(UserNotFoundException)).unwrap()   

This code works but have several ugliness including

  • As lambda could not accept raise, we could not help to have a weird wrapper function like _raise
  • We broke map_err() signature as the function accept a callable to return Err value

So basically, I’d like to ask having such API like below

def get_user():
    # Return user when Ok otherwise raise UserNotFoundException which accepting error
    return _get_user().ok_or(UserNotFoundException)

I don’t think ok_or() is a right API name to reflect the feature (and is different from ok_or() in Rust), so please understand the intention only. It seems opposite API of as_result() as it translates Exception to Result and now I’m asking a API for Result.err to Exception.

I think introducing Try API may be the right one to implement such feature but do not aware of the project’s road map, so any viable solution would be appreciated.

Thanks!

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:10 (8 by maintainers)

github_iconTop GitHub Comments

1reaction
ileixecommented, Jun 17, 2022

@wbolster yes, i think so.

1reaction
wbolstercommented, Jun 13, 2022

💡 just brainstorming…

i don’t quite like how this proposed api makes it almost inevitable to use a lambda construct for something that’s supposed to do something simple. (fwiw, i don’t like lambdas in general, in python at least.)

maybe this could handle Type[BaseException] in a special way? so that it can be either a callable (such as a lambda) or an exception class directly?

res.unwrap_or_raise(ValueError)  # raise ValueError()

however, nice errors, which this is about in the first place, typically require more than just an exception class, e.g. a message:

res.unwrap_or_raise(ValueError, "foo")  # raise ValueError("foo")

but sometimes it’s not just a string, so maybe also this?

res.unwrap_or_raise(MyException, *args, **kwargs)  # raise MyException(*args, **kwargs)

… but these may be hard to type correctly.

passing an exception instance could work but would always construct it, even when it’s not needed:

res.unwrap_or_raise(ValueError("foo"))  # hmmm :/
Read more comments on GitHub >

github_iconTop Results From Across the Web

Chained Exceptions in Java - Baeldung
In this article, we'll have a very brief look at what Exception is and go in depth about discussing the chained exceptions in...
Read more >
How to chain exceptions in javascript (ie add cause like in java)
The way I'm printing exceptions makes it nice and clean looking: console.log(e.stack). prints something like this: My error message: SomeError <some line> ...
Read more >
Python | Raising an Exception to Another Exception
To chain exceptions, use the raise from statement instead of a simple raise statement. This will give you information about both errors.
Read more >
Understanding Java Exception Chaining with Code Examples
The main purpose of exception chaining is to preserve the original exception when it propagates across multiple logical layers in a program.
Read more >
Considering When To Throw Errors, Why To Chain Them, And ...
Ideally, each method has to catch all exceptions possible and rethrow them through chaining. Once again, catch everything, chain, and ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found