How to convert a constant into a ProgramError type in Rust/Anchor when returning in a function?

32 Views Asked by At

Learning Rust and Anchor here. I'm trying to return a ProgramError for a specific scenario in this program, but when using the into() method inside #[program] an error msg is shown.

I've checked the documentation:

Here's the error message:

the trait bound anchor_lang::prelude::ProgramError: From<ErrorCode> is not satisfied the following other types implement trait From<T>: <anchor_lang::prelude::ProgramError as From>
<anchor_lang::prelude::ProgramError as From<anchor_lang::error::Error>> <anchor_lang::prelude::ProgramError as Fromstd::io::Error> <anchor_lang::prelude::ProgramError as From> required for ErrorCode to implement Into<anchor_lang::prelude::ProgramError>

Here the program code.

#[program]
pub mod solana_twitter {
    use super::*;
    pub fn send_tweet(
        // SendTweet was used as generic type to link the context to this function
        ctx: Context<SendTweet>,
        topic: String,
        content: String,
    ) -> ProgramResult {
        let tweet: &mut Account<Tweet> = &mut ctx.accounts.tweet;
        // Signer is used to guarantee that the account is owned by the author
        let author: &Signer = &ctx.accounts.author;
        let clock: Clock = Clock::get().unwrap();

        if topic.chars().count() > 50 {
            return Err(ErrorCode::TopicTooLong.into());
        }
        if content.chars().count() > 280 {
            return Err(ErrorCode::ContentTooLong.into());
        }

        tweet.author = *author.key;
        tweet.timestamp = clock.unix_timestamp;
        tweet.topic = topic;
        tweet.content = content;

        Ok(())
    }
}

The ErrorCode enum.

#[error_code]
pub enum ErrorCode {
    #[msg("The provided topic should be 50 characters long maximum.")]
    TopicTooLong,
    #[msg("The provided content should be 280 characters long maximum.")]
    ContentTooLong,
}
1

There are 1 best solutions below

3
Sarthak Singh On

You are suppose to use the anchor_lang::err macro to wrap the error.

it should be

if topic.chars().count() > 50 {
    return err!(ErrorCode::TopicTooLong);
}
if content.chars().count() > 280 {
    return err!(ErrorCode::ContentTooLong);
}

See: https://www.anchor-lang.com/docs/errors

Also I think you should be returning Result<()> instead of ProgramResult.