How to factor out a library with custom error type

I have a rust file that I keep copying across into each new project that I'm doing. I'd like to factor it out and turn it into a library, but I'm unsure how to.

The file contains a number of trais like this:

pub trait TryDiv<RHS>: Sized {
    fn try_floor_div(self, rhs: RHS) -> Result<Self, ProgramError>;
}

And a number of implementations like this:

// for u32
impl TryDiv<u32> for u32 {
    fn try_floor_div(self, rhs: u32) -> Result<Self, ProgramError> {
        self.checked_div(rhs)
            .ok_or(ErrorCode::ArithmeticError.into())
    }
}

// for u64
impl TryDiv<u64> for u64 {
    fn try_floor_div(self, rhs: u64) -> Result<Self, ProgramError> {
        self.checked_div(rhs)
            .ok_or(ErrorCode::ArithmeticError.into())
    }
}

TLDR it's not doing anything smart, simply saves me from having to type out the errors every time.

It would have been simple to factor out had it not been for the custom error type that I'm passing in. I'm unsure how to go about it:

  • I thought about including the error in the library, but it needs to sit inside a particular enum for another package (achor) to use it correctly
  • I thought about maybe instantiating the library somehow, passing in the error, but I'm not experienced enough on my own

What's the best way to do this? Examples would help.

Also, if there's an existing crate somewhere that does this and I'm reinventing the wheel, pls let me know:)

When you have a library in which the code can generate an error, the correct thing to do is define a custom error type inside the library. I don't see what the problem is with that approach. In particular, I don't understand what you mean by this:

You can use error types defined in a 3rd-party library just fine. That's obviously not the problem here, what am I missing?

I see what you're saying and it makes total sense to define custom error types inside the lib.

What confuses me is the fact that Anchor basically uses a macro for its error types, which looks like this:

#[error]
pub enum ErrorCode {
    #[msg("failed to perform some math operation safely")]
    ArithmeticError,
    #[msg("another error")]
    AnotherError,
    #[msg("another error")]
    AnotherError,
}

And one of those errors is the one I need to use inside the lib. So do I define 2 enums (one inside lib, one outside) and merge them somehow? Is that even possible?

I don't think you have to create two error types. Just create a single error type within your library that wraps the Anchor ErrorCode, then impl From<ErrorCode> for YourLibError and call it a day.

2 Likes

Thanks, this seems super obvious once you said it!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.