How do I "throw" a tokio_postgres::Error?

409 views Asked by At

I want to create a validation when I'm creating a new user. Already an email error must be returned. Like this:

pub async fn insert_usuario(usuario: &Usuario) -> Result<&Usuario, Error> {
    let mut fetch_usuario= Usuario { nome: String::new(), email: String::new(), senha: String::new()};
    
    match get_usuario_by_email(&usuario.email).await {
        Ok(u) =>{fetch_usuario=u},
        Err(e) =>{println!("Erro {}",e)}
    }

    if !fetch_usuario.email.eq(""){
        println!("Email {} already exists.", fetch_usuario.email);
        return tokio_postgres::Error("User already exists")
    }

    let client = get_client().await;
    client.execute("insert into usuario (nome, email, senha) values ($1, $2, $3);", 
        &[&usuario.nome, &usuario.email, &usuario.senha])
        .await?;
    Ok(usuario)
}

But compiling shows:

error[E0423]: cannot initialize a tuple struct which contains private fields
   --> src/lib.rs:95:16
    |
95  |         return tokio_postgres::Error("User already exists")
    |                ^^^^^^^^^^^^^^^^^^^^^
    |
note: constructor is not visible here due to private fields
   --> /Users/msansone/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-postgres-0.7.5/src/error/mod.rs:366:18
    |
366 | pub struct Error(Box<ErrorInner>);
    |                  ^^^^^^^^^^^^^^^ private field
help: consider importing one of these items instead
    |

How can I generate a new/custom tokio_postgres::Error?

1

There are 1 answers

0
Cerberus On

The documentation doesn't show any way to create an error, so it's likely not intended to be generated outside of the library.

That makes sense, however. "User already exists" is not a database error, like the server being down, - it's the logical error, and you probably shouldn't treat them the same way anyway. It's expected that you create your own error type, probably using either thiserror (for structured errors) or anyhow (for opaque ones).