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.
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.