Movatterモバイル変換


[0]ホーム

URL:


Module error

core

Moduleerror 

1.81.0 ·Source
Expand description

Interfaces for working with Errors.

§Error Handling In Rust

The Rust language provides two complementary systems for constructing /representing, reporting, propagating, reacting to, and discarding errors.These responsibilities are collectively known as “error handling.” Thecomponents of the first system, the panic runtime and interfaces, are mostcommonly used to represent bugs that have been detected in your program. Thecomponents of the second system,Result, the error traits, and userdefined types, are used to represent anticipated runtime failure modes ofyour program.

§The Panic Interfaces

The following are the primary interfaces of the panic system and theresponsibilities they cover:

The following are the primary interfaces of the error system and theresponsibilities they cover:

  • Result (Propagating, Reacting)
  • TheError trait (Reporting)
  • User defined types (Constructing / Representing)
  • match anddowncast (Reacting)
  • The question mark operator (?) (Propagating)
  • The partially stableTry traits (Propagating, Constructing)
  • Termination (Reporting)

§Converting Errors into Panics

The panic and error systems are not entirely distinct. Often times errorsthat are anticipated runtime failures in an API might instead represent bugsto a caller. For these situations the standard library provides APIs forconstructing panics with anError as its source.

These functions are equivalent, they either return the inner value if theResult isOk or panic if theResult isErr printing the inner erroras the source. The only difference between them is that withexpect youprovide a panic error message to be printed alongside the source, whereasunwrap has a default message indicating only that you unwrapped anErr.

Of the two,expect is generally preferred since itsmsg field allows youto convey your intent and assumptions which makes tracking down the sourceof a panic easier.unwrap on the other hand can still be a good fit insituations where you can trivially show that a piece of code will neverpanic, such as"127.0.0.1".parse::<std::net::IpAddr>().unwrap() or earlyprototyping.

§Common Message Styles

There are two common styles for how people wordexpect messages. Usingthe message to present information to users encountering a panic(“expect as error message”) or using the message to present informationto developers debugging the panic (“expect as precondition”).

In the former case the expect message is used to describe the error thathas occurred which is considered a bug. Consider the following example:

// Read environment variable, panic if it is not presentletpath = std::env::var("IMPORTANT_PATH").unwrap();

In the “expect as error message” style we would use expect to describethat the environment variable was not set when it should have been:

letpath = std::env::var("IMPORTANT_PATH")    .expect("env variable `IMPORTANT_PATH` is not set");

In the “expect as precondition” style, we would instead describe thereason weexpect theResult should beOk. With this style we wouldprefer to write:

letpath = std::env::var("IMPORTANT_PATH")    .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`");

The “expect as error message” style does not work as well with thedefault output of the std panic hooks, and often ends up repeatinginformation that is already communicated by the source error beingunwrapped:

thread 'main' panicked at src/main.rs:4:6:env variable `IMPORTANT_PATH` is not set: NotPresent

In this example we end up mentioning that an env variable is not set,followed by our source message that says the env is not present, theonly additional information we’re communicating is the name of theenvironment variable being checked.

The “expect as precondition” style instead focuses on source codereadability, making it easier to understand what must have gone wrong insituations where panics are being used to represent bugs exclusively.Also, by framing our expect in terms of what “SHOULD” have happened toprevent the source error, we end up introducing new information that isindependent from our source error.

thread 'main' panicked at src/main.rs:4:6:env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`: NotPresent

In this example we are communicating not only the name of theenvironment variable that should have been set, but also an explanationfor why it should have been set, and we let the source error display asa clear contradiction to our expectation.

Hint: If you’re having trouble remembering how to phraseexpect-as-precondition style error messages remember to focus on the word“should” as in “env variable should be set by blah” or “the given binaryshould be available and executable by the current user”.

Structs§

RequestExperimental
Request supports generic, type-driven access to data. Its use is currently restricted to thestandard library in cases where trait authors wish to allow trait implementors to share genericinformation across trait boundaries. The motivating and prototypical use case iscore::error::Error which would otherwise require a method per concrete type (eg.std::backtrace::Backtrace instance that implementors want to expose to users).
SourceExperimental
An iterator over anError and its sources.

Traits§

Error
Error is a trait representing the basic expectations for error values,i.e., values of typeE inResult<T, E>.

Functions§

request_refExperimental
Requests a reference of typeT from the givenimpl Error.
request_valueExperimental
Requests a value of typeT from the givenimpl Error.

[8]ページ先頭

©2009-2025 Movatter.jp