liveBook · Manning

Error propagation

As explained in Rust Servers, Services, and Apps

Error propagation is the technique of passing an operation's failure result to a caller so that a higher-level component can handle it.

Error propagation passes a failed database operation from low-level access code to a calling HTTP handler instead of panicking. In Rust, replacing unwrap() with ? returns the failure early, while Result communicates that the function may fail. section 5.4

Propagating a course-query failure

Declare get_courses_for_tutor_db as returning Result<Vec<Course>, EzyTutorError>, then use .await? on the SQLx query. The handler awaits that function and maps success to an HTTP 200 JSON response. From<SQLxError> converts database failures into EzyTutorError values that the handler can process. section 5.4

Listing 5.4 Error handling in the method to retrieve courses for a tutor
pub async fn get_courses_for_tutor_db(
    pool: &PgPool,
    tutor_id: i32,
) -> Result<Vec<Course>, EzyTutorError> {        #1
    // Prepare SQL statement
    let course_rows = sqlx::query!(
        "SELECT tutor_id, course_id, course_name,
        posted_time FROM ezy_course_c5 where tutor_id = $1",
        tutor_id
    )
    .fetch_all(pool)
    .await?;                                     #2
    // Extract result
 
    let courses: Vec<Course> = course_rows
        .iter()
        .map(|course_row| Course {
            course_id: course_row.course_id,
            tutor_id: course_row.tutor_id,
            course_name: course_row.course_name.clone(),
            posted_time: Some(chrono::NaiveDateTime::from(
            course_row.posted_time.unwrap())),
        })
        .collect();
    match courses.len() {                        #3
        0 => Err(EzyTutorError::NotFound(
            "Courses not found for tutor".into(),
        )),
        _ => Ok(courses),
    }
}

Inspect the complete database-access method showing its Result signature and propagated SQLx query. section 5.4

How Rust Servers, Services, and Apps covers it

How deep it goes
Contrasts unwrap() with ?, then applies Result signatures and error conversions without detailing Rust error internals.
Examples
Uses tutor course retrieval, SQLx queries, EzyTutorError conversions, curl requests, and handler tests.
What it assumes
Assumes familiarity with Rust functions and web-service code while introducing Result-based database failure handling in context.
What you can do after
Apply error propagation via Rust's question mark operator and custom From implementations in an Actix web service.
How it connects
Connects Result types, database access, HTTP handlers, SQLx errors, and custom error conversion.

Also explained in

Compare how 5 books explain error propagation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust Servers, Services, and Apps. The section links point to the parts of the book it draws on.