pub struct Catcher {
pub name: Option<Cow<'static, str>>,
pub base: Origin<'static>,
pub code: Option<u16>,
pub handler: Box<dyn Handler>,
}
Expand description
An error catching route.
Catchers are routes that run when errors are produced by the application.
They consist of a Handler
and an optional status code to match against
arising errors. Errors arise from the the following sources:
- A failing guard.
- A failing responder.
- A forwarding guard.
- Routing failure.
Each error or forward is paired with a status code. Guards and responders
indicate the status code themselves via their Err
and Outcome
return
value. A complete routing failure is always a 404
. Rocket invokes the
error handler for the catcher with an error’s status code, or in the case of
every route resulting in a forward, the last forwarded status code.
§Error Handler Restrictions
Because error handlers are a last resort, they should not fail to produce a
response. If an error handler does fail, Rocket invokes its default 500
error catcher. Error handlers cannot forward.
§Routing
If a route fails by returning an error Outcome
, Rocket routes the
erroring request to the highest precedence catcher among all the catchers
that match. Precedence is determined by the catcher’s base, which is
provided as the first argument to Rocket::register()
. Catchers with more
non-empty segments have a higher precedence.
Rocket provides built-in defaults, but default
catchers can also be registered. A default catcher is a catcher with no
explicit status code: None
.
§Collisions
Two catchers are said to collide if there exists an error that matches
both catchers. Colliding catchers present a routing ambiguity and are thus
disallowed by Rocket. Because catchers can be constructed dynamically,
collision checking is done at ignite
time,
after it becomes statically impossible to register any more catchers on an
instance of Rocket
.
§Built-In Default
Rocket’s provides a built-in default catcher that can handle all errors. It
produces HTML or JSON, depending on the value of the Accept
header. As
such, catchers only need to be registered if an error needs to be handled in
a custom fashion. The built-in default never conflicts with any
user-registered catchers.
§Code Generation
Catchers should rarely be constructed or used directly. Instead, they are
typically generated via the catch
attribute, as follows:
#[macro_use] extern crate rocket;
use rocket::Request;
use rocket::http::Status;
#[catch(500)]
fn internal_error() -> &'static str {
"Whoops! Looks like we messed up."
}
#[catch(404)]
fn not_found(req: &Request) -> String {
format!("I couldn't find '{}'. Try something else?", req.uri())
}
#[catch(default)]
fn default(status: Status, req: &Request) -> String {
format!("{} ({})", status, req.uri())
}
#[launch]
fn rocket() -> _ {
rocket::build().register("/", catchers![internal_error, not_found, default])
}
A function decorated with #[catch]
may take zero, one, or two arguments.
It’s type signature must be one of the following, where R:
Responder
:
See the catch
documentation for full details.
Fields§
§name: Option<Cow<'static, str>>
The name of this catcher, if one was given.
base: Origin<'static>
The mount point.
code: Option<u16>
The HTTP status to match against if this route is not default
.
handler: Box<dyn Handler>
The catcher’s associated error handler.
Implementations§
source§impl Catcher
impl Catcher
sourcepub fn new<S, H>(code: S, handler: H) -> Catcher
pub fn new<S, H>(code: S, handler: H) -> Catcher
Creates a catcher for the given status
, or a default catcher if
status
is None
, using the given error handler. This should only be
used when routing manually.
§Examples
use rocket::request::Request;
use rocket::catcher::{Catcher, BoxFuture};
use rocket::response::Responder;
use rocket::http::Status;
fn handle_404<'r>(status: Status, req: &'r Request<'_>) -> BoxFuture<'r> {
let res = (status, format!("404: {}", req.uri()));
Box::pin(async move { res.respond_to(req) })
}
fn handle_500<'r>(_: Status, req: &'r Request<'_>) -> BoxFuture<'r> {
Box::pin(async move{ "Whoops, we messed up!".respond_to(req) })
}
fn handle_default<'r>(status: Status, req: &'r Request<'_>) -> BoxFuture<'r> {
let res = (status, format!("{}: {}", status, req.uri()));
Box::pin(async move { res.respond_to(req) })
}
let not_found_catcher = Catcher::new(404, handle_404);
let internal_server_error_catcher = Catcher::new(500, handle_500);
let default_error_catcher = Catcher::new(None, handle_default);
§Panics
Panics if code
is not in the HTTP status code error range [400, 600)
.
sourcepub fn map_base<'a, F>(self, mapper: F) -> Result<Self, Error<'static>>
pub fn map_base<'a, F>(self, mapper: F) -> Result<Self, Error<'static>>
Maps the base
of this catcher using mapper
, returning a new
Catcher
with the returned base.
mapper
is called with the current base. The returned String
is used
as the new base if it is a valid URI. If the returned base URI contains
a query, it is ignored. Returns an error if the base produced by
mapper
is not a valid origin URI.
§Example
use rocket::request::Request;
use rocket::catcher::{Catcher, BoxFuture};
use rocket::response::Responder;
use rocket::http::Status;
fn handle_404<'r>(status: Status, req: &'r Request<'_>) -> BoxFuture<'r> {
let res = (status, format!("404: {}", req.uri()));
Box::pin(async move { res.respond_to(req) })
}
let catcher = Catcher::new(404, handle_404);
assert_eq!(catcher.base.path(), "/");
let catcher = catcher.map_base(|_| format!("/bar")).unwrap();
assert_eq!(catcher.base.path(), "/bar");
let catcher = catcher.map_base(|base| format!("/foo{}", base)).unwrap();
assert_eq!(catcher.base.path(), "/foo/bar");
let catcher = catcher.map_base(|base| format!("/foo ? {}", base));
assert!(catcher.is_err());
Trait Implementations§
Auto Trait Implementations§
impl !Freeze for Catcher
impl !RefUnwindSafe for Catcher
impl Send for Catcher
impl Sync for Catcher
impl Unpin for Catcher
impl !UnwindSafe for Catcher
Blanket Implementations§
source§impl<'a, T> AsTaggedExplicit<'a> for Twhere
T: 'a,
impl<'a, T> AsTaggedExplicit<'a> for Twhere
T: 'a,
source§impl<'a, T> AsTaggedImplicit<'a> for Twhere
T: 'a,
impl<'a, T> AsTaggedImplicit<'a> for Twhere
T: 'a,
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
source§unsafe fn clone_to_uninit(&self, dst: *mut T)
unsafe fn clone_to_uninit(&self, dst: *mut T)
clone_to_uninit
)source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
§impl<T> IntoCollection<T> for T
impl<T> IntoCollection<T> for T
source§impl<T> IntoEither for T
impl<T> IntoEither for T
source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moresource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moresource§impl<T> Paint for Twhere
T: ?Sized,
impl<T> Paint for Twhere
T: ?Sized,
source§fn fg(&self, value: Color) -> Painted<&T>
fn fg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self
with the foreground set to
value
.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like red()
and
green()
, which have the same functionality but are
pithier.
§Example
Set foreground color to white using fg()
:
use yansi::{Paint, Color};
painted.fg(Color::White);
Set foreground color to white using white()
.
use yansi::Paint;
painted.white();
source§fn bright_black(&self) -> Painted<&T>
fn bright_black(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightBlack
.
§Example
println!("{}", value.bright_black());
source§fn bright_red(&self) -> Painted<&T>
fn bright_red(&self) -> Painted<&T>
source§fn bright_green(&self) -> Painted<&T>
fn bright_green(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightGreen
.
§Example
println!("{}", value.bright_green());
source§fn bright_yellow(&self) -> Painted<&T>
fn bright_yellow(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightYellow
.
§Example
println!("{}", value.bright_yellow());
source§fn bright_blue(&self) -> Painted<&T>
fn bright_blue(&self) -> Painted<&T>
source§fn bright_magenta(&self) -> Painted<&T>
fn bright_magenta(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightMagenta
.
§Example
println!("{}", value.bright_magenta());
source§fn bright_cyan(&self) -> Painted<&T>
fn bright_cyan(&self) -> Painted<&T>
source§fn bright_white(&self) -> Painted<&T>
fn bright_white(&self) -> Painted<&T>
Returns self
with the
fg()
set to
Color::BrightWhite
.
§Example
println!("{}", value.bright_white());
source§fn bg(&self, value: Color) -> Painted<&T>
fn bg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self
with the background set to
value
.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like on_red()
and
on_green()
, which have the same functionality but
are pithier.
§Example
Set background color to red using fg()
:
use yansi::{Paint, Color};
painted.bg(Color::Red);
Set background color to red using on_red()
.
use yansi::Paint;
painted.on_red();
source§fn on_primary(&self) -> Painted<&T>
fn on_primary(&self) -> Painted<&T>
source§fn on_magenta(&self) -> Painted<&T>
fn on_magenta(&self) -> Painted<&T>
source§fn on_bright_black(&self) -> Painted<&T>
fn on_bright_black(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightBlack
.
§Example
println!("{}", value.on_bright_black());
source§fn on_bright_red(&self) -> Painted<&T>
fn on_bright_red(&self) -> Painted<&T>
source§fn on_bright_green(&self) -> Painted<&T>
fn on_bright_green(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightGreen
.
§Example
println!("{}", value.on_bright_green());
source§fn on_bright_yellow(&self) -> Painted<&T>
fn on_bright_yellow(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightYellow
.
§Example
println!("{}", value.on_bright_yellow());
source§fn on_bright_blue(&self) -> Painted<&T>
fn on_bright_blue(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightBlue
.
§Example
println!("{}", value.on_bright_blue());
source§fn on_bright_magenta(&self) -> Painted<&T>
fn on_bright_magenta(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightMagenta
.
§Example
println!("{}", value.on_bright_magenta());
source§fn on_bright_cyan(&self) -> Painted<&T>
fn on_bright_cyan(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightCyan
.
§Example
println!("{}", value.on_bright_cyan());
source§fn on_bright_white(&self) -> Painted<&T>
fn on_bright_white(&self) -> Painted<&T>
Returns self
with the
bg()
set to
Color::BrightWhite
.
§Example
println!("{}", value.on_bright_white());
source§fn attr(&self, value: Attribute) -> Painted<&T>
fn attr(&self, value: Attribute) -> Painted<&T>
Enables the styling Attribute
value
.
This method should be used rarely. Instead, prefer to use
attribute-specific builder methods like bold()
and
underline()
, which have the same functionality
but are pithier.
§Example
Make text bold using attr()
:
use yansi::{Paint, Attribute};
painted.attr(Attribute::Bold);
Make text bold using using bold()
.
use yansi::Paint;
painted.bold();
source§fn underline(&self) -> Painted<&T>
fn underline(&self) -> Painted<&T>
Returns self
with the
attr()
set to
Attribute::Underline
.
§Example
println!("{}", value.underline());
source§fn rapid_blink(&self) -> Painted<&T>
fn rapid_blink(&self) -> Painted<&T>
Returns self
with the
attr()
set to
Attribute::RapidBlink
.
§Example
println!("{}", value.rapid_blink());
source§fn quirk(&self, value: Quirk) -> Painted<&T>
fn quirk(&self, value: Quirk) -> Painted<&T>
Enables the yansi
Quirk
value
.
This method should be used rarely. Instead, prefer to use quirk-specific
builder methods like mask()
and
wrap()
, which have the same functionality but are
pithier.
§Example
Enable wrapping using .quirk()
:
use yansi::{Paint, Quirk};
painted.quirk(Quirk::Wrap);
Enable wrapping using wrap()
.
use yansi::Paint;
painted.wrap();
source§fn clear(&self) -> Painted<&T>
👎Deprecated since 1.0.1: renamed to resetting()
due to conflicts with Vec::clear()
.
The clear()
method will be removed in a future release.
fn clear(&self) -> Painted<&T>
resetting()
due to conflicts with Vec::clear()
.
The clear()
method will be removed in a future release.source§fn whenever(&self, value: Condition) -> Painted<&T>
fn whenever(&self, value: Condition) -> Painted<&T>
Conditionally enable styling based on whether the Condition
value
applies. Replaces any previous condition.
See the crate level docs for more details.
§Example
Enable styling painted
only when both stdout
and stderr
are TTYs:
use yansi::{Paint, Condition};
painted.red().on_yellow().whenever(Condition::STDOUTERR_ARE_TTY);