Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why did error not trigger when println was run?

I was trying to trace the error in my Rust API code. When I ran it, it showed the following in the terminal:

Server running on localhost:3000
auth
auth err1
...

Notice auth err1 was printed from inside .ok_or() in my code below, but the StatusCode::BAD_REQUEST was not triggered as I got 200 OK back. Why? What happened?

pub async fn auth<T>(mut request: Request<T>, next: Next<T>) -> Result<Response, StatusCode> {
    println!("auth");
    let token = request
        .headers()
        .typed_get::<Authorization<Bearer>>()
        .ok_or({
            println!("auth err1");
            StatusCode::BAD_REQUEST
        })?
        .token()
        .to_owned();
        //other code to connect to DB and retrieve user data...
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Since you put println!("auth err1") in a block it will immediately be executed no matter if typed_get returned Some or None.
You need to make it a closure and use ok_or_else to only print in the None case:

    .ok_or_else(|| {
        println!("auth err1");
        StatusCode::BAD_REQUEST
    })?
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading