How to manually return a Result<(), Box>?

后端 未结 4 993
傲寒
傲寒 2021-02-02 16:05

I want to return an error from a function in case a condition is true:

use std::error::Error;

pub fn run() -> Result<(), Box> {
    //         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-02 16:39

    I am new to Rust, but here is my dirty hack to return custom errors, given that the function is set to return Result<(), Box>:

    fn serve(config: &Config, stream: TcpStream) -> Result<(), Box> {
        // ...
        if request_is_bad() {
            // This returns immediately a custom "Bad request" error
            Err("Bad request")?;
        }
        // ...
    }
    

提交回复
热议问题