rsRustPrimer
< Back to module

Error handling

Running project · riskforge

Project: load a portfolio

riskforge can compute now, but its trades are hard-coded. We will read them from a CSV file. That is typically where errors show up: a missing column, a mistyped number, an unknown instrument type. The goal: never panic, and say exactly which line is wrong and why.

data/portfolio.csv
id,counterparty,instrument,strike,direction,quantity
1,ACME,forward,100,long,1000
2,ACME,forward,105,short,800
3,Globex,call,120,long,200
4,Initech,put,95,short,100
src/loader.rs
#[derive(Debug, PartialEq)]
pub enum ParseError {
WrongFieldCount { expected: usize, found: usize },
InvalidNumber { field: &'static str, value: String },
UnknownInstrument(String),
UnknownDirection(String),
}
#[derive(Debug, PartialEq)]
pub struct LoadError {
pub line: usize,
pub error: ParseError,
}
const FIELD_COUNT: usize = 6;
fn parse_number(field: &'static str, value: &str) -> Result<f64, ParseError> {
value.parse().map_err(|_| ParseError::InvalidNumber { field, value: value.to_string() })
}
/// Une ligne CSV devient (contrepartie, champs utiles), ou une erreur explicite.
pub fn parse_line(line: &str) -> Result<(String, f64, f64), ParseError> {
let fields: Vec<&str> = line.split(',').map(|f| f.trim()).collect();
if fields.len() != FIELD_COUNT {
return Err(ParseError::WrongFieldCount { expected: FIELD_COUNT, found: fields.len() });
}
match fields[2] {
"forward" | "call" | "put" => {}
other => return Err(ParseError::UnknownInstrument(other.to_string())),
}
let strike = parse_number("strike", fields[3])?;
let quantity = parse_number("quantity", fields[5])?;
Ok((fields[1].to_string(), strike, quantity))
}
/// Charge toutes les lignes ; la première erreur est renvoyée avec son numéro de ligne.
pub fn load(csv: &str) -> Result<Vec<(String, f64, f64)>, LoadError> {
let mut rows = Vec::new();
for (index, line) in csv.lines().enumerate() {
let line_number = index + 1;
if line_number == 1 || line.trim().is_empty() {
continue; // en-tête et lignes vides
}
let row = parse_line(line).map_err(|error| LoadError { line: line_number, error })?;
rows.push(row);
}
Ok(rows)
}
fn main() {
let csv = "id,counterparty,instrument,strike,direction,quantity\n1,ACME,forward,100,long,1000\n2,ACME,swap,105,short,800";
println!("{:?}", load(csv));
}
A shortened version: in the repository, parse_line builds a real Trade (direction included) and load_portfolio fills a Portfolio directly.

Two layers of errors. ParseError describes what is wrong with a line, without knowing where it is. LoadError adds the context: the line number. Each layer adds what only it knows, thanks to map_err then ?. The final message reads like: line 3: unknown instrument: swap.

src/main.rs
use std::error::Error;
use std::fs;
fn main() -> Result<(), Box<dyn Error>> {
let csv = fs::read_to_string("data/portfolio.csv")?;
println!("{} caractères lus", csv.len());
Ok(())
}
fs::read_to_string returns an io::Result: a missing file becomes a clean error, and ? bubbles it up to main.

Your turn

Make load also skip comment lines, those starting with # (after any leading spaces).

src/main.rs
fn load(csv: &str) -> Vec<String> {
let mut rows = Vec::new();
for (index, line) in csv.lines().enumerate() {
if index == 0 || line.trim().is_empty() {
continue;
}
rows.push(line.trim().to_string());
}
rows
}
fn main() {
let csv = "id,counterparty\n1,ACME\n # trade annulé\n2,Globex";
println!("{:?}", load(csv)); // ["1,ACME", "2,Globex"]
}