Russo
Russo

Reputation: 2972

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...
}

Upvotes: 0

Views: 67

Answers (1)

cafce25
cafce25

Reputation: 27186

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
    })?

Upvotes: 3

Related Questions