【问题标题】:the trait `From<Errors>` is not implemented for `anchor_lang::prelude::ProgramError``anchor_lang::prelude::ProgramError` 没有实现特征 `From<Errors>`
【发布时间】:2022-06-16 14:08:51
【问题描述】:

我正在尝试在 solana 智能合约中编写错误枚举:

use anchor_lang::prelude::*;

#[error]
pub enum Errors {
    #[msg("User cannot be created, missing data")]
    CannotCreateUser,

    #[msg("Cannot have more than 5 likes")]
    ReachedMaxLikes,

}

我是这样用的

if image.likes == NUMBER_OF_ALLOWED_LIKES_SPACE  {
            return Err(Errors::ReachedMaxLikes.into());
        }

我收到此错误

return Err(Errors::ReachedMaxLikes.into());
   |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `From<Errors>` is not implemented for `anchor_lang::prelude::ProgramError`
   |

我使用[ProgramError]#[derive(ProgramError)] 而不是[error],但错误消息仍然存在

【问题讨论】:

    标签: rust blockchain smartcontracts solana


    【解决方案1】:

    根据documentation中的示例:

    use anchor_lang::prelude::*;
    
    #[error_code]
    pub enum Errors {
        #[msg("User cannot be created, missing data")]
        CannotCreateUser,
    
        #[msg("Cannot have more than 5 likes")]
        ReachedMaxLikes,
    
    }
    
    

    然后:

    if image.likes == NUMBER_OF_ALLOWED_LIKES_SPACE  {
       return Err(error!(Errors::ReachedMaxLikes));
    }
    

    【讨论】:

    • 我还是有同样的错误。
    【解决方案2】:

    在你的代码上试试这些:

    • 在枚举上使用#[error_code]
    • 抛出这样的错误:return err!(Errors::ReachedMaxLikes);
    • 再次检查您的程序方法签名是否返回 anchor_lang::Result,而不是 std 一个

    【讨论】:

      猜你喜欢
      • 2015-10-08
      • 1970-01-01
      • 2022-12-07
      • 2021-07-18
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 2021-04-25
      • 1970-01-01
      相关资源
      最近更新 更多