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




