Return Rust Result from update or query call

It would be really nice to be able to return a Result from an update or query call, like this:

#[update]
fn test() -> Result<String, Box<dyn Error>> {
  Ok("it works".to_string()")
}

That way I could easily use the ? operator. Does anyone know how to do this elegantly? There are some Candid traits not implemented for this, seems like we would want Result handled out of the box for Rust.

1 Like

Why do you return Box<dyn Error>?
I mean, this should work, but it depends on what is the Error type in your code.

Am assuming he wants to bubble up any error and let caller handle it. Is there a limitation? Was expecting that we could just build structure of function pointers to any concrete piece of machine code for each method we want to implement given that Rust is supported.

Is there any clean documentation that shows what basic features we cannot use in Rust … there seems to be a number of recent comments suggesting entry level limitations.

This would be helpful. Thanks!

1 Like

You should always keep in mind, that your interfacing data will pass through the serialization pipeline. Since there is no information about how one could serialize this generic Error type, it shouldn’t be possible to define such a return type. So for me it works as intended.

Another question is why can’t we write something like this:

#[update]
pub fn test() -> Result<(), Box<dyn CandidType>> {
    Ok(())
}

But, I’m not sure if I would ever want to write such a code. What should I type in .did file then? How would someone else integrate with this function?

2 Likes

And I’m also not sure, why would you use as an Error anything else except of String or enum.

I think it should be more than enough to express almost any kind of situation and still be able to use ? syntax:

#[derive(CandidType, Deserialize)]
pub enum Error {
    BadThingHappened,
    AnotherBadThing,
    SomeGenericBadThing(String),
}

#[update]
pub fn test() -> Result<(), Error> {
    Err(Error::BadThingHappened)?;

    Ok(())
}
1 Like

Well the whole idea of ? as u know is to say return Err if Err, otherwise unwrap OK. If u know every possible variant of course u can list them.

Interfacing data has to pass thru serialization. OK …can guess the answer to my previous question.

1 Like

A Vec or similar would be necessary in situations where you would like to report multiple errors.

2 Likes