This article is a sample from Zero To Production In Rust, a book on backend development in Rust.
 You can get a copy of the book on zero2prod.com.

Error Handling In Rust - A Deep Dive

submited by
Style Pass
2021-06-05 14:30:04

This article is a sample from Zero To Production In Rust, a book on backend development in Rust. You can get a copy of the book on zero2prod.com. Subscribe to the newsletter to be notified when a new episode is published.

To send a confirmation email you have to stitch together multiple operations: validation of user input, email dispatch, various database queries. They all have one thing in common: they may fail.

In Chapter 6 we discussed the building blocks of error handling in Rust - Result and the ? operator. We left many questions unanswered: how do errors fit within the broader architecture of our application? What does a good error look like? Who are errors for? Should we use a library? Which one?

We are trying to insert a row into the subscription_tokens table in order to store a newly-generated token against a subscriber_id. execute is a fallible operation: we might have a network issue while talking to the database, the row we are trying to insert might violate some table constraints (e.g. uniqueness of the primary key), etc.

The caller of execute most likely wants to be informed if a failure occurs - they need to react accordingly, e.g. retry the query or propagate the failure upstream using ?, as in our example.

Leave a Comment