pub struct Error<'v> {
pub name: Option<NameBuf<'v>>,
pub value: Option<Cow<'v, str>>,
pub kind: ErrorKind<'v>,
pub entity: Entity,
}
Expand description
A form error, potentially tied to a specific form field.
An Error
is returned by FromForm
, FromFormField
, and validate
procedures, typically as a collection of Errors
. It potentially
identifies a specific field that triggered the error via Error::name
and
the field’s value via Error::value
.
An Error
can occur because of a field’s value that failed to parse or
because other parts of a field or form were malformed; the Error::entity
identifies the part of the form that resulted in the error.
Constructing
An Error
can be constructed via Error::validation()
,
Error::custom()
, or anything that an ErrorKind
can be constructed
from. See ErrorKind
.
use rocket::form::Error;
fn at_most_10_not_even() -> Result<usize, Error<'static>> {
// Using `From<PartIntError> => ErrorKind::Int`.
let i: usize = "foo".parse()?;
if i > 10 {
// `From<(Option<isize>, Option<isize>)> => ErrorKind::OutOfRange`
return Err((None, Some(10isize)).into());
} else if i % 2 == 0 {
return Err(Error::validation("integer cannot be even"));
}
Ok(i)
}
Setting Field Metadata
When implementing FromFormField
, nothing has to be done for a field’s
metadata to be set: the blanket FromForm
implementation sets it
automatically.
When constructed from an ErrorKind
, the entity is set to
Entity::default_for()
by default. Occasionally, the error’s entity
may
need to be set manually. Return what would be useful to the end-consumer.
Matching Errors to Fields
To determine whether an error corresponds to a given field, use
Error::is_for()
. For example, to get all of the errors that correspond
to the field foo.bar
, you might write the following:
use rocket::form::Errors;
let errors = Errors::new();
let errors_for_foo = errors.iter().filter(|e| e.is_for("foo.bar"));
Serialization
When a value of this type is serialized, a struct
or map with the
following fields is emitted:
field | type | description |
---|---|---|
name | Option<&str> | the erroring field’s name, if known |
value | Option<&str> | the erroring field’s value, if known |
entity | &str | string representation of the erroring Entity |
msg | &str | concise message of the error |
Fields
name: Option<NameBuf<'v>>
The name of the field, if it is known.
value: Option<Cow<'v, str>>
The field’s value, if it is known.
kind: ErrorKind<'v>
The kind of error that occurred.
entity: Entity
The entitiy that caused the error.
Implementations
sourceimpl<'v> Error<'v>
impl<'v> Error<'v>
sourcepub fn custom<E>(error: E) -> Self where
E: Error + Send + 'static,
pub fn custom<E>(error: E) -> Self where
E: Error + Send + 'static,
Creates a new Error
with ErrorKind::Custom
.
For validation errors, use Error::validation()
.
Example
use rocket::form::Error;
fn from_fmt(error: std::fmt::Error) -> Error<'static> {
Error::custom(error)
}
sourcepub fn validation<S: Into<Cow<'v, str>>>(msg: S) -> Self
pub fn validation<S: Into<Cow<'v, str>>>(msg: S) -> Self
Creates a new Error
with ErrorKind::Validation
and message msg
.
Example
use rocket::form::error::{Error, ErrorKind, Entity};
let error = Error::validation("invalid foo: need bar");
assert!(matches!(error.kind, ErrorKind::Validation(_)));
assert_eq!(error.entity, Entity::Value);
sourcepub fn with_entity(self, entity: Entity) -> Self
pub fn with_entity(self, entity: Entity) -> Self
Consumes self
and returns a new Error
with the entity set to
entity
.
Example
use rocket::form::error::{Error, ErrorKind, Entity};
let error = Error::from(ErrorKind::Missing);
assert_eq!(error.entity, Entity::Field);
let error = error.with_entity(Entity::Key);
assert_eq!(error.entity, Entity::Key);
sourcepub fn set_entity(&mut self, entity: Entity)
pub fn set_entity(&mut self, entity: Entity)
Sets the error’s entity to entity.
Example
use rocket::form::error::{Error, ErrorKind, Entity};
let mut error = Error::from(ErrorKind::Missing);
assert_eq!(error.entity, Entity::Field);
error.set_entity(Entity::Key);
assert_eq!(error.entity, Entity::Key);
sourcepub fn with_name<N: Into<NameBuf<'v>>>(self, name: N) -> Self
pub fn with_name<N: Into<NameBuf<'v>>>(self, name: N) -> Self
Consumes self
and returns a new Error
with the field name set to
name
if it was not already set.
Example
use rocket::form::error::{Error, ErrorKind};
let error = Error::from(ErrorKind::Missing);
assert!(error.name.is_none());
let error = error.with_name("foo");
assert_eq!(error.name.as_ref().unwrap(), "foo");
let error = error.with_name("bar");
assert_eq!(error.name.as_ref().unwrap(), "foo");
sourcepub fn set_name<N: Into<NameBuf<'v>>>(&mut self, name: N)
pub fn set_name<N: Into<NameBuf<'v>>>(&mut self, name: N)
Sets the field name of self
to name
if it is not already set.
Example
use rocket::form::error::{Error, ErrorKind};
let mut error = Error::from(ErrorKind::Missing);
assert!(error.name.is_none());
error.set_name("foo");
assert_eq!(error.name.as_ref().unwrap(), "foo");
let error = error.with_name("bar");
assert_eq!(error.name.as_ref().unwrap(), "foo");
sourcepub fn with_value(self, value: &'v str) -> Self
pub fn with_value(self, value: &'v str) -> Self
Consumes self
and returns a new Error
with the value set to value
if it was not already set.
Example
use rocket::form::error::{Error, ErrorKind};
let error = Error::from(ErrorKind::Missing);
assert!(error.value.is_none());
let error = error.with_value("foo");
assert_eq!(error.value.as_ref().unwrap(), "foo");
let error = error.with_value("bar");
assert_eq!(error.value.as_ref().unwrap(), "foo");
sourcepub fn set_value(&mut self, value: &'v str)
pub fn set_value(&mut self, value: &'v str)
Set the field value of self
to value
if it is not already set.
Example
use rocket::form::error::{Error, ErrorKind};
let mut error = Error::from(ErrorKind::Missing);
assert!(error.value.is_none());
error.set_value("foo");
assert_eq!(error.value.as_ref().unwrap(), "foo");
error.set_value("bar");
assert_eq!(error.value.as_ref().unwrap(), "foo");
sourcepub fn is_for<N: AsRef<Name>>(&self, name: N) -> bool
pub fn is_for<N: AsRef<Name>>(&self, name: N) -> bool
Returns true
if this error applies to a field named name
. This is
different than simply comparing name
.
Unlike Error::is_for_exactly()
, this method returns true
if the
error’s field name is a prefix of name
. This is typically what is
desired as errors apply to a field and its children: a.b
applies to
the nested fields a.b.c
, a.b.d
and so on.
Returns false
if self
has no field name.
Example
use rocket::form::Error;
// returns `false` without a field name
let error = Error::validation("bad `foo`");
assert!(!error.is_for_exactly("a.b"));
// `a.b` is a prefix all of these field names
let error = error.with_name("a.b");
assert!(error.is_for("a.b"));
assert!(error.is_for("a[b]"));
assert!(error.is_for("a.b.c"));
assert!(error.is_for("a.b[c]"));
assert!(error.is_for("a.b.c[d]"));
assert!(error.is_for("a.b.c.d.foo"));
// ...but not of these.
assert!(!error.is_for("a.c"));
assert!(!error.is_for("a"));
sourcepub fn is_for_exactly<N: AsRef<Name>>(&self, name: N) -> bool
pub fn is_for_exactly<N: AsRef<Name>>(&self, name: N) -> bool
Returns true
if this error applies to exactly the field named name
.
Returns false
if self
has no field name.
Unlike Error::is_for()
, this method returns true
only when the
error’s field name is exactly name
. This is not typically what is
desired.
Example
use rocket::form::Error;
// returns `false` without a field name
let error = Error::validation("bad `foo`");
assert!(!error.is_for_exactly("a.b"));
let error = error.with_name("a.b");
assert!(error.is_for_exactly("a.b"));
assert!(error.is_for_exactly("a[b]"));
// does not return `true` when the name is a prefix
assert!(!error.is_for_exactly("a.b.c"));
assert!(!error.is_for_exactly("a.b[c]"));
assert!(!error.is_for_exactly("a.b.c[d]"));
assert!(!error.is_for_exactly("a.b.c.d.foo"));
// does not return `true` when the name is different
assert!(!error.is_for("a.c"));
assert!(!error.is_for("a"));
sourcepub fn status(&self) -> Status
pub fn status(&self) -> Status
Returns the most reasonable Status
associated with this error. These
are:
PayloadTooLarge
if the error kind is:InvalidLength
with min ofNone
Multpart(FieldSizeExceeded | StreamSizeExceeded)
InternalServerError
if the error kind is:Unknown
BadRequest
if the error kind is:Io
with anentity
ofForm
UnprocessableEntity
otherwise
Example
use rocket::form::error::{Error, ErrorKind, Entity};
use rocket::http::Status;
let error = Error::validation("bad `foo`");
assert_eq!(error.status(), Status::UnprocessableEntity);
let error = Error::from((None, Some(10u64)));
assert_eq!(error.status(), Status::PayloadTooLarge);
let error = Error::from(ErrorKind::Unknown);
assert_eq!(error.status(), Status::InternalServerError);
// default entity for `io::Error` is `Form`.
let error = Error::from(std::io::Error::last_os_error());
assert_eq!(error.status(), Status::BadRequest);
let error = error.with_entity(Entity::Value);
assert_eq!(error.status(), Status::UnprocessableEntity);
Trait Implementations
sourceimpl IntoOwned for Error<'_>
impl IntoOwned for Error<'_>
sourcefn into_owned(self) -> Self::Owned
fn into_owned(self) -> Self::Owned
Converts self
into an owned version of itself.
impl<'v> StructuralPartialEq for Error<'v>
Auto Trait Implementations
impl<'v> !RefUnwindSafe for Error<'v>
impl<'v> Send for Error<'v>
impl<'v> !Sync for Error<'v>
impl<'v> Unpin for Error<'v>
impl<'v> !UnwindSafe for Error<'v>
Blanket Implementations
impl<'a, T> AsTaggedExplicit<'a> for T where
T: 'a,
impl<'a, T> AsTaggedExplicit<'a> for T where
T: 'a,
fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self>
impl<'a, T> AsTaggedImplicit<'a> for T where
T: 'a,
impl<'a, T> AsTaggedImplicit<'a> for T where
T: 'a,
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T> Instrument for T
impl<T> Instrument for T
sourcefn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
sourcefn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
sourceimpl<T> IntoCollection<T> for T
impl<T> IntoCollection<T> for T
sourcefn into_collection<A>(self) -> SmallVec<A> where
A: Array<Item = T>,
fn into_collection<A>(self) -> SmallVec<A> where
A: Array<Item = T>,
Converts self
into a collection.
fn mapped<U, F, A>(self, f: F) -> SmallVec<A> where
F: FnMut(T) -> U,
A: Array<Item = U>,
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
fn vzip(self) -> V
sourceimpl<T> WithSubscriber for T
impl<T> WithSubscriber for T
sourcefn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
Attaches the provided Subscriber
to this type, returning a
WithDispatch
wrapper. Read more
sourcefn with_current_subscriber(self) -> WithDispatch<Self>
fn with_current_subscriber(self) -> WithDispatch<Self>
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more