Skip to main content

Error

Enum Error 

Source
pub enum Error {
    NotFound,
    BadRequest(String),
    Unauthorized,
    Forbidden,
    Invalid(Vec<FieldError>),
    Conflict(String),
    PayloadTooLarge(String),
    TooManyRequests,
    Internal(String),
}
Expand description

Handler error: an HTTP status plus, for client errors, a message the user may see.

Internal details are logged to the Worker logs (Workers Logs), never sent to the client. With the html feature it renders as an HTML error page (validation errors listed as full messages); JSON endpoints return ApiError, which converts from it with ?: {"error": {"status": 404, "message": "Not found"}}. ? also converts a [worker::Error] into Error::Internal.

VariantStatusMessage sent
NotFound404Not found
BadRequest400its message
Unauthorized401Unauthorized
Forbidden403Forbidden
Invalid422Validation failed plus the field errors
Conflict409its message
PayloadTooLarge413its message
TooManyRequests429Too many requests. Try again later.
Internal500Internal server error (message logged)

§Examples

use ocre::{Error, OptionExt, Result};

fn find(id: i64) -> Result<&'static str> {
    match id {
        0 => Err(Error::bad_request("id must be positive")),
        1 => Ok("First post"),
        _ => None.or_404(),
    }
}

assert_eq!(find(1).unwrap(), "First post");
assert!(matches!(find(2), Err(Error::NotFound)));
assert_eq!(find(0).unwrap_err().to_string(), "bad request: id must be positive");

Variants§

§

NotFound

404 Not Found: the record or route does not exist.

§

BadRequest(String)

400 Bad Request, with a message shown to the user.

§

Unauthorized

401 Unauthorized: missing or invalid credentials (password, session, token).

JSON responses add WWW-Authenticate: Bearer.

§

Forbidden

403 Forbidden: signed in, but not allowed to do this.

§

Invalid(Vec<FieldError>)

422 Unprocessable Entity: failed validations, one entry per field error.

Built by Validator::finish. JSON answers group messages by field: "fields": {"title": ["can't be blank"]}.

§

Conflict(String)

409 Conflict: the record changed since it was read (optimistic locking with a lock_version column), or a unique key already exists; the message is shown to the user.

Generated update functions of models with a lock_version field return it for a stale version (Rails’ ActiveRecord::StaleObjectError).

§

PayloadTooLarge(String)

413 Payload Too Large: the request body is over a limit, with a message shown to the user.

See storage::Multipart.

§

TooManyRequests

429 Too Many Requests: a rate limit was hit.

Returned by security::rate_limit.

§

Internal(String)

500 Internal Server Error; the message goes to the Worker logs only.

Logged as [ocre] <message> when the response is built; the client sees Internal server error.

Implementations§

Source§

impl Error

Source

pub fn bad_request(message: impl Into<String>) -> Self

Builds a 400 Error::BadRequest whose message is shown to the user.

§Examples
let err = ocre::Error::bad_request("limit must be a number");
assert_eq!(err.to_string(), "bad request: limit must be a number");
Source

pub fn internal(message: impl Into<String>) -> Self

Builds a 500 Error::Internal whose message is logged, never shown to the user.

Name the fix in the message, as Ocre’s own errors do.

§Examples
let err = ocre::Error::internal("KV binding `CACHE` is missing");
assert!(matches!(&err, ocre::Error::Internal(message) if message.contains("CACHE")));
Source

pub fn is_taken(&self) -> bool

Whether the error says a unique value is already used: a “has already been taken” validation error (generated models check unique fields before writing), D1’s UNIQUE constraint failed (two requests raced past the check), or a Conflict.

Query::create_or_first uses it to fall back to the existing row.

§Examples
use ocre::{Error, FieldError};

assert!(Error::Invalid(vec![FieldError::new("email", "has already been taken")]).is_taken());
assert!(Error::internal("D1_ERROR: UNIQUE constraint failed: users.email").is_taken());
assert!(!Error::Invalid(vec![FieldError::new("email", "can't be blank")]).is_taken());
assert!(!Error::NotFound.is_taken());

Trait Implementations§

Source§

impl Debug for Error

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Error

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for Error

1.30.0 · Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0:

use the Display impl or to_string()

1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<Error> for ApiError

Source§

fn from(err: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for Error

Source§

fn from(err: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for Error

Source§

fn from(err: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for Error

Source§

fn from(err: Error) -> Self

Converts to this type from the input type.
Source§

impl IntoResponse for Error

HTML error page. JSON endpoints return ApiError instead.

The page is a bare <h1>404</h1><p>Not found</p>; the response carries an ErrorPage extension so error_page can render the app’s own template instead.

Source§

fn into_response(self) -> Response

Create a response.

Auto Trait Implementations§

§

impl Freeze for Error

§

impl RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl UnsafeUnpin for Error

§

impl UnwindSafe for Error

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<S, T> Upcast<T> for S
where T: UpcastFrom<S> + ?Sized, S: ?Sized,

Source§

fn upcast(&self) -> &T
where Self: ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider ref type within the Wasm bindgen generics type system. Read more
Source§

fn upcast_into(self) -> T
where Self: Sized + ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider type within the Wasm bindgen generics type system. Read more
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V