Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 39 ยท Commands and Events

Command Errors: Result, thiserror and Custom Error Types

Handle failures in Tauri commands: return Result, make error types serializable, use thiserror and enums, and catch rejected invoke() Promises in TypeScript.

Real commands fail: a file is missing, input is invalid, a lock is poisoned. Tauri's answer is the standard Rust one, Result. This lesson shows how to turn Rust errors into useful, structured rejections on the JavaScript side.

Result in a command

A command that returns Result<T, E> resolves its Promise with T on success and rejects with E on failure.

Rust
#[tauri::command]
fn divide(a: f64, b: f64) -> Result<f64, String> {
    if b == 0.0 {
        Err("cannot divide by zero".into())
    } else {
        Ok(a / b)
    }
}
TypeScript
try {
  const value = await invoke<number>("divide", { a: 10, b: 0 });
} catch (error) {
  console.error(error); // "cannot divide by zero"
}

String errors are the simplest option and fine for small apps. The cost is that the frontend can only show text; it cannot tell which kind of error happened without parsing the message.

The error must be serializable

The error value has to cross the bridge as JSON, so the error type must implement Serialize. Many standard error types (for example std::io::Error) do not. The following does not compile:

Rust
#[tauri::command]
fn read_note(path: String) -> Result<String, std::io::Error> {   // error: Serialize not implemented
    std::fs::read_to_string(path)
}

The simplest fix is to convert errors to strings: .map_err(|e| e.to_string()).

Rust
#[tauri::command]
fn read_note(path: String) -> Result<String, String> {
    std::fs::read_to_string(&path).map_err(|e| format!("cannot read {path}: {e}"))
}

A proper error enum with thiserror

For anything larger, define your own enum, derive thiserror::Error for friendly messages and implement Serialize manually:

Rust
use serde::{Serialize, Serializer};

#[derive(Debug, thiserror::Error)]
enum AppError {
    #[error("note {0} was not found"0} was not found")]
    NotFound(u32),
    #[error("title is empty")]
    EmptyTitle,
    #[error(transparent)]
    Io(#[from] std::io::Error),
}

impl Serialize for AppError {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.to_string())
    }
}

#[tauri::command]
fn load_note(id: u32) -> Result<String, AppError> {
    if id == 0 {
        return Err(AppError::NotFound(id));
    }
    let text = std::fs::read_to_string(format!("note-{id}.txt"))?; // io::Error -> AppError via From
    Ok(text)
}

Three pieces cooperate here:

  • #[error("...")] creates the human-readable message (the Display impl).
  • #[from] lets ? convert an io::Error into AppError::Io automatically.
  • The manual Serialize sends the message as a string. This is enough for most apps.

thiserror is an extra crate you add with cargo add thiserror. It is only a convenience; you could write Display and From by hand.

Structured errors for the frontend

If the UI must react differently to each error (highlight a field, offer a retry), send structure instead of one string. Use serde's tagging:

Rust
#[derive(Debug, thiserror::Error, serde::Serialize)]
#[serde(tag = "kind", content = "message", rename_all = "camelCase")]
enum AppError {
    #[error("note {0} was not found"0} was not found")]
    NotFound(u32),
    #[error("title is empty")]
    EmptyTitle,
}

That serializes to { "kind": "notFound", "message": 5 } or { "kind": "emptyTitle" }, and in TypeScript you can model it as a discriminated union:

TypeScript
type AppError =
  | { kind: "notFound"; message: number }
  | { kind: "emptyTitle" };

try {
  await invoke("load_note", { id: 5 });
} catch (e) {
  const err = e as AppError;
  switch (err.kind) {
    case "notFound": showToast(`No note ${err.message}`); break;
    case "emptyTitle": markFieldInvalid("title"); break;
  }
}

Argument errors

If JavaScript sends the wrong shape (a missing key, a string where a number is expected), the command never runs and the Promise rejects with a message such as invalid args 'noteId' for command 'load_note': .... Treat it as a programmer bug: fix the call. Make parameters Option<T> when they are truly optional.

Panics

A panic! or an .unwrap() on None inside a command is a bug, not an error path. Depending on settings, it can crash the app or poison a mutex so later calls fail. Prefer Result and ?, and reserve unwrap() for cases that truly cannot fail.

Try it: Result and rejection (stand-in)

The stand-in models the mapping: a Rust Err becomes a rejected Promise, Ok resolves. The command returns a Result-like object and invoke converts it.

Node.js Stand-in: Ok resolves, Err rejects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Try it: structured errors and a switch (stand-in)

This one models the tagged-enum idea. Notice how the frontend branches on kind instead of parsing text.

Node.js Stand-in: tagged error objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Design guidance

  • Return Result from any command that can fail; do not hide failures in Option or sentinel values.
  • Keep messages safe for users and free of secrets or full file paths you do not want shown.
  • Log the detailed error in Rust (eprintln! or the log plugin) and send a concise one to the frontend.
  • Use a single AppError enum for the whole app so every command shares one pattern.

Continue with Async commands.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to the invoke() Promise when a command returns Err?

    Err is serialized and the JavaScript Promise is rejected, so you catch it with try/catch.
  2. 2. Why does returning Result<String, std::io::Error> fail to compile?

    The error crosses the bridge as JSON, so it needs Serialize. Convert to String or implement it.
  3. 3. What does #[from] on an error variant enable?

    It generates a From impl so ? converts the source error into your enum.
  4. 4. Why use a tagged error enum?

    Structured errors give the UI reliable information to react to.

Summary

  • Return Result<T, E>: Ok resolves the Promise and Err rejects it.
  • The error type must implement Serialize; convert with map_err or write your own enum.
  • thiserror plus #[from] makes ? convenient.
  • Tag errors with #[serde(tag = "kind")] for typed handling in TypeScript.
  • Avoid panics inside commands.

Next: Async commands