Errors, packages and async · 12 min · free lesson

try/catch vs Result

throw and try/catch become Result<T, E>: failure is part of the return type, ? propagates it, and panics are reserved for bugs.

Core idea

Return Result for a failure the caller can act on, propagate it with ?, and keep panics such as unwrap for bugs and broken invariants.

JavaScript (Node.js) and Rust, side by side

JavaScript (Node.js) Number reads "" as 0 and "0x50" as 80, and the only signal of failure is a thrown Error.
function parsePort(text) {
  const n = Number(text);
  if (!Number.isInteger(n) || n < 1 || n > 65535) {
    throw new Error(`invalid port: ${JSON.stringify(text)}`);
  }
  return n;
}

for (const input of ["8080", "", "0x50", "70000"]) {
  try {
    console.log(input, "->", parsePort(input));
  } catch (err) {
    console.log(input, "->", err.message);
  }
}
Rust ? returns the wrapped parse error early, the range check produces its own variant, and main matches both.
use std::num::ParseIntError;

#[derive(Debug)]
enum PortError {
    NotANumber(ParseIntError),
    OutOfRange(u32),
}

fn parse_port(text: &str) -> Result<u16, PortError> {
    let n: u32 = text.parse().map_err(PortError::NotANumber)?;
    match u16::try_from(n) {
        Ok(port) if port != 0 => Ok(port),
        _ => Err(PortError::OutOfRange(n)),
    }
}

fn main() {
    for input in ["8080", "", "0x50", "70000"] {
        match parse_port(input) {
            Ok(port) => println!("{input} -> {port}"),
            Err(err) => println!("{input} -> {err:?}"),
        }
    }
}
What changes
JavaScript (Node.js)Rust
Any function may throw, and its signature does not say so.-> Result<u16, PortError> declares the failure, and callers must handle it.
catch (err) receives anything, often just a message.A match on an error enum tells the cases apart by type.
An uncaught exception bubbles up invisibly.? propagates an Err explicitly, at each call site.
Number("") is 0, and Number("0x50") is 80."".parse::<u32>() fails with kind Empty, and "0x50" with InvalidDigit.

Understand it

In JavaScript any function may throw anything, and nothing in its signature says so. A caller learns that parsePort throws by reading its code or by watching it crash. Rust puts failure in the type: fn parse_port(text: &str) -> Result<u16, PortError> returns either Ok(port) or Err(reason), and the caller cannot reach the u16 without deciding what to do about the error.

The error type is yours to design. An enum such as PortError { NotANumber(ParseIntError), OutOfRange(u32) } lets a caller tell the cases apart with match instead of comparing message strings, and it can wrap the lower-level error as its cause. map_err converts one error type into another, and the ? operator returns the Err early, like an exception propagating, but visibly at every call site and only from a function that itself returns a compatible Result.

Panics are not exceptions. unwrap(), expect(), indexing out of bounds and integer overflow in a debug build panic: the thread unwinds, or the process aborts if the build sets panic = "abort". Use them for bugs, where continuing would be wrong, not for invalid user input. A Result is for situations the caller can reasonably handle: bad text, a missing file, a refused connection.

Parsing stops being lenient as well. Number("") is 0 and Number("0x50") is 80, while "".parse::<u32>() is an Err of kind Empty and "0x50" one of kind InvalidDigit. One surprise runs the other way: integer parse accepts a leading +, so validate the exact format first when your contract forbids a sign.

The JavaScript (Node.js) habit, written in Rust

This is how the JavaScript (Node.js) version usually looks on a first attempt in Rust. Predict what rustc says before you read the explanation.

fn main() {
    let input = "70000";
    let port: u16 = input.parse().unwrap();
    println!("{port}");
}

Practise this code in Playground ↗

Try it

Port the JavaScript parseDuration shown at the top of solution.rs. Accept ASCII digits followed by s, m or h. Return DurationError::BadFormat for anything else, including a missing number or a sign, and DurationError::TooLong above 86,400 seconds, even when the number does not fit an integer type. In the Crabrix app, open the compiler lab and complete the supplied function in solution.rs. The reading question is a separate exercise.

What success looks like: The local compiler accepts the changed solution and the separate verification harness passes every case, including 24h, +5s and a number too large for u32. Printing a success message alone does not complete this lab.

Check your understanding

In the practice code, what does unwrap() do when parse returns Err?

Reveal the answer
  1. It panics: the thread unwinds, or the process aborts if panics are configured to abort
  2. It returns the Err to the caller automatically, like an uncaught throw bubbling up
  3. It returns 0, as Number does for bad input

unwrap is a deliberate crash on Err. Handing the error back to the caller is what ? does.

Go deeper

Common misconception: “unwrap() is like letting the exception propagate to a caller's try/catch.”

unwrap() panics. To let the caller handle the error, return a Result and use ?, which hands the Err back.

  1. Read the signature: parse_port returns Result<u16, PortError>. Both kinds of failure are variants a caller can match on.
  2. Follow each input: "" and "0x50" fail in parse, and ? returns them wrapped in NotANumber. "70000" parses as a u32, but u16::try_from fails, giving OutOfRange(70000).
  3. Compare with evidence: Run it: 8080 -> 8080, then NotANumber with kinds Empty and InvalidDigit, then OutOfRange(70000). JavaScript accepted 0x50 as port 80.

Transfer challenge: Implement std::fmt::Display for PortError so that main can print invalid port: out of range (70000). Then write fn parse_address(text: &str) -> Result<(String, u16), PortError> that splits host:port and uses ? on parse_port.

Connections

  • TypeScript interfaces vs traits: Nominal traits instead of structural interfaces
  • npm and package.json vs Cargo: package.json and npm mapped to Cargo
Side-by-side comparison: the JavaScript (Node.js) version on the left, the Rust version on the right, then 4 rows naming what changes.
try/catch vs Result: the same task in JavaScript (Node.js) and in Rust, with the differences that matter.
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: try/catch vs Result (courseId "rust-for-nodejs-developers", lessonId "node-try-catch-to-result")
Link: https://crabrix.com/learn/rust-for-nodejs-developers/node-try-catch-to-result/
Goal: Return Result for a failure the caller can act on, propagate it with ?, and keep panics such as unwrap for bugs and broken invariants.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-nodejs-developers/node-try-catch-to-result) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.