Menu
CoddyTech

Error Contracts

Lesson 28 of 48 in Coddy's Rust for Ruby Developers course.

Ruby custom exception classes can distinguish failure categories for rescue, while Rust error enums encode alternatives in an explicit return type. Match on meaningful variants when callers need different recovery behavior, and reserve human-readable messages for presentation. The source catches its FormatError and the target matches its enum failure. A Result return type does not guarantee rollback any more than raise does: assignments performed before an error remain unless the code restores them. For a reject-without-change contract, validate the prospective state before committing it. Propagating an error should preserve information instead of turning every failure into a valid zero or empty string.

Ruby: complete program

class FormatError < StandardError; end
def parse_mode(text)
  raise FormatError, "format" unless text == "ready"
  text
end
begin
  parse_mode("bad")
rescue FormatError => error
  puts error.message
end

Rust: complete program

#[derive(Debug)]
enum FormatError { Unsupported }
fn check_format(name: &str) -> Result<(), FormatError> {
    if name == "plain" { Ok(()) } else { Err(FormatError::Unsupported) }
}
fn main() {
    match check_format("binary") {
        Ok(()) => println!("ready"),
        Err(FormatError::Unsupported) => println!("format"),
    }
}

Failure representation and transactional state updates are separate design decisions.

challenge icon

Challenge

Easy

Implement public DebitError variants NonPositive and Insufficient, deriving Debug and PartialEq, and pub fn debit(balance: &mut i32, amount: i32) -> Result<i32, DebitError> in account.rs. Starting balances are nonnegative and arithmetic fits i32. Reject an amount of zero or less with NonPositive; otherwise reject an amount greater than the balance with Insufficient. Every failure leaves balance unchanged. On success subtract amount and return the new balance. Input is starting balance followed by debit amounts. solve applies them in order and returns final|statuses, with statuses ok:new, nonpositive or insufficient, comma-separated. With no amounts the suffix is empty.

Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.

Your code goes in exercise.rs, account.rs. main.rs holds the supplied input/output code and cannot be edited.

Try it yourself

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod account;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // BEGIN PUBLIC API PROBES
let mut balance = 37;
assert_eq!(account::debit(&mut balance, 12), Ok(25));
assert_eq!(account::debit(&mut balance, 26), Err(account::DebitError::Insufficient));
assert_eq!(balance, 25);
assert_eq!(account::debit(&mut balance, -4), Err(account::DebitError::NonPositive));
assert_eq!(balance, 25);
assert_eq!(account::debit(&mut balance, 0), Err(account::DebitError::NonPositive));
assert_eq!(balance, 25);
assert_eq!(account::debit(&mut balance, 25), Ok(0));
assert_eq!(account::debit(&mut balance, 1), Err(account::DebitError::Insufficient));
assert_eq!(balance, 0);

    // END PUBLIC API PROBES
    println!("{}", exercise::solve(&input));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Rust for Ruby Developers

Practice on your own: Online Rust compiler