Skip to content

Commit c4bdf17

Browse files
committed
add ToStr trait
1 parent dbd235c commit c4bdf17

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

program-error/src/lib.rs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,57 @@ impl From<ProgramError> for u64 {
306306
}
307307
}
308308

309+
/// A trait for converting a program error to a `&str`.
310+
pub trait ToStr {
311+
fn to_str<E>(&self) -> &'static str
312+
where
313+
E: 'static + ToStr + TryFrom<u32>;
314+
}
315+
316+
impl ToStr for ProgramError {
317+
fn to_str<E>(&self) -> &'static str
318+
where
319+
E: 'static + ToStr + TryFrom<u32>,
320+
{
321+
match self {
322+
Self::Custom(error) => {
323+
if let Ok(custom_error) = E::try_from(*error) {
324+
custom_error.to_str::<E>()
325+
} else {
326+
"Error: Unknown"
327+
}
328+
}
329+
Self::InvalidArgument => "Error: InvalidArgument",
330+
Self::InvalidInstructionData => "Error: InvalidInstructionData",
331+
Self::InvalidAccountData => "Error: InvalidAccountData",
332+
Self::AccountDataTooSmall => "Error: AccountDataTooSmall",
333+
Self::InsufficientFunds => "Error: InsufficientFunds",
334+
Self::IncorrectProgramId => "Error: IncorrectProgramId",
335+
Self::MissingRequiredSignature => "Error: MissingRequiredSignature",
336+
Self::AccountAlreadyInitialized => "Error: AccountAlreadyInitialized",
337+
Self::UninitializedAccount => "Error: UninitializedAccount",
338+
Self::NotEnoughAccountKeys => "Error: NotEnoughAccountKeys",
339+
Self::AccountBorrowFailed => "Error: AccountBorrowFailed",
340+
Self::MaxSeedLengthExceeded => "Error: MaxSeedLengthExceeded",
341+
Self::InvalidSeeds => "Error: InvalidSeeds",
342+
Self::BorshIoError => "Error: BorshIoError",
343+
Self::AccountNotRentExempt => "Error: AccountNotRentExempt",
344+
Self::UnsupportedSysvar => "Error: UnsupportedSysvar",
345+
Self::IllegalOwner => "Error: IllegalOwner",
346+
Self::MaxAccountsDataAllocationsExceeded => "Error: MaxAccountsDataAllocationsExceeded",
347+
Self::InvalidRealloc => "Error: InvalidRealloc",
348+
Self::MaxInstructionTraceLengthExceeded => "Error: MaxInstructionTraceLengthExceeded",
349+
Self::BuiltinProgramsMustConsumeComputeUnits => {
350+
"Error: BuiltinProgramsMustConsumeComputeUnits"
351+
}
352+
Self::InvalidAccountOwner => "Error: InvalidAccountOwner",
353+
Self::ArithmeticOverflow => "Error: ArithmeticOverflow",
354+
Self::Immutable => "Error: Immutable",
355+
Self::IncorrectAuthority => "Error: IncorrectAuthority",
356+
}
357+
}
358+
}
359+
309360
impl From<u64> for ProgramError {
310361
fn from(error: u64) -> Self {
311362
match error {

0 commit comments

Comments
 (0)