2

How do we handle the custom errors returned from calling a function in the client side? here is my function:

pub fn create_resume(ctx: Context<CreateResume>, name: String, age: u8, skills: Vec<String>) -> Result<()>{
        if name.len() > 20{
            return err!(Error::ExceedsLimit)
        }
        if age > 100{
            return err!(Error::ExceedsLimit)
        }
        if skills.len() > 10{
            return err!(Error::ExceedsLimit)
        }
        for skill in skills.iter(){
            if skill.len() > 10{
                return err!(Error::ExceedsLimit)
            }
        }
        let resume = &mut ctx.accounts.resume;
        resume.wallet = ctx.accounts.signer.key();
        resume.bump = *ctx.bumps.get("resume").unwrap();
        resume.name = name;
        resume.age = age;
        resume.skills = skills;
        Ok(())
    }

The error that I have defined

#[error_code]
pub enum Error{
    #[msg("Failed to verify authority")]
    Unauthorized,
    #[msg("Exceeds limit")]
    ExceedsLimit,
    #[msg("Skill doesn't exist")]
    DoesNotExist,
}

How do I handle the error in the client side? can anyone show me an example?

1 Answer 1

2

use try { } catch (e) { } and check e.message. That should include the error msg. e.g. "Failed to verify authority"

try {
    const tx = await program.rpc.CreateResume(name, age, skills,{
       accounts: {
       payer: wallet.publicKey,
    },})
    console.log('Your transaction signature', tx)
} catch (e: any) {
    if e.message.includes("Failed to verify authority") { .. }
    else if e.message.includes("Exceeds limit") { .. }
    else if e.message.includes("Skill doesn't exist") { .. }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.