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

should have document on best practice about how to throw custom error #1405

Closed
loynoir opened this issue Sep 23, 2023 · 3 comments
Closed

should have document on best practice about how to throw custom error #1405

loynoir opened this issue Sep 23, 2023 · 3 comments

Comments

@loynoir
Copy link

loynoir commented Sep 23, 2023

Seperated document issue from previous

#1404

From my newbee understanding

typescript throw error equivalent

    throw new Error("msg");

should be

    panic!("msg");

But typescript throw custom error equivalent seems very complicated.

class OddEvenError extends Error { }

function castOdd(): Odd {
    throw new OddEvenError('not odd')
}
    struct Odd(u32);

    #[derive(Debug)]
    struct OddEvenError {
        message: String,
    }

    impl OddEvenError {
        fn new(message: &str) -> Self {
            OddEvenError {
                message: message.to_string(),
            }
        }
    }

    impl Error for OddEvenError {}

    impl std::fmt::Display for OddEvenError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "{}", self.message)
        }
    }

    fn cast_odd() -> Result<Odd, Box<dyn Error>> {
        Err(Box::new(OddEvenError::new("not odd")))
    }

    cast_odd().expect("err");
@loynoir loynoir changed the title should have document best practice on how to throw custom error should have document on best practice about how to throw custom error Sep 23, 2023
@bjorn3
Copy link
Member

bjorn3 commented Sep 23, 2023

The reference describes the rust language itself, not what idiomatic rust is, nor how to learn it as beginner. The rust book is meant for learning rust. In this specific case Chapter 9: Error Handling is relevant.

@ehuss
Copy link
Contributor

ehuss commented Sep 25, 2023

As mentioned, the reference isn't intended for new learners, or for how to map concepts from another language to Rust. If you are having questions on how to do things, I suggest trying one of the user forums such as https://users.rust-lang.org/.

@ehuss ehuss closed this as not planned Won't fix, can't repro, duplicate, stale Sep 25, 2023
@loynoir
Copy link
Author

loynoir commented Sep 25, 2023

Ah, sorry.

I mis-understood as this repo is for rust document team.

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

No branches or pull requests

3 participants