Urgent.News

What's breaking now, across thousands of outlets.

Tech

Two Tiny Utils for the Result Pattern

In the world of Rust programming, developers often favor the Result pattern over using multiple try and catch blocks found in TypeScript. The Result pattern is an enum with two variants: Ok(T) for successful outcomes and Err(E) for errors. This enum forces the caller to handle both success and error cases, ensuring that no errors are left unattended. Two handy helpers that the author uses universally in their Rust projects are tryCatch and safeExec.

The tryCatch function wraps a function, whether it returns a result or throws an exception, into a Result. This allows for cleaner error handling when dealing with functions that might throw exceptions. On the other hand, safeExec takes a function that already returns a Result, ensuring that no exceptions are thrown. If the function behaves as expected, safeExec simply returns the Result.

However, if an error occurs, safeExec catches it and wraps it back into the same Result structure. This pattern helps maintain a consistent error handling approach throughout the codebase, regardless of whether a function inherently returns a Result or throws exceptions.

Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at daviddalbusco.com →

More in Tech

More from Monday 7 September →