[actix web] return error in middleware

Hello Everyone :slight_smile:

i wrote i middleware that checks for user token, and decides wither to allow access to resource or not,
the call function looks like this

    fn call(&mut self, mut req: ServiceRequest) -> Self::Future {
        let mut svc = self.service.clone();

        Box::pin(async move {
            let mut body = BytesMut::new();
            let mut stream = req.take_payload();

            while let Some(chunk) = stream.next().await {
                body.extend_from_slice(&chunk?);
            }

            let json: Value = serde_json::from_str(std::str::from_utf8(&body[..])?)?;
            let mut is_valid = false;

            match json.get("token") {
                Some(token) => {
                    match Token::check(web::Json(Token { token: token.to_string() })) {
                        Ok(true) => { is_valid = true; },
                        Ok(false) => { is_valid = false; },
                        Err(_) => { is_valid = false; }
                    }
                },
                None => { is_valid = false; }
            }

            if is_valid {
                return Ok(svc.call(req).await?)
            }

        // RETURN A F*** ERROR
        })
    }

i spent 5 hours now trying to figure out how to return an error,this is my first application in rust and actix

i will appreciate any guidance, thank you

How is Self::Future defined? I assume you have declared which error type you are using somewhere outside the snippet. In general I believe you should be able to just put

Err(some_error_constructor_here)

at the line where you want to fail, but the exact error constructor you need depends on the error type you have chosen for the future.

1 Like