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.
| Variant | Status | Message sent |
|---|---|---|
NotFound | 404 | Not found |
BadRequest | 400 | its message |
Unauthorized | 401 | Unauthorized |
Forbidden | 403 | Forbidden |
Invalid | 422 | Validation failed plus the field errors |
Conflict | 409 | its message |
PayloadTooLarge | 413 | its message |
TooManyRequests | 429 | Too many requests. Try again later. |
Internal | 500 | Internal 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.
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
impl Error
Sourcepub fn bad_request(message: impl Into<String>) -> Self
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");Sourcepub fn internal(message: impl Into<String>) -> Self
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")));Sourcepub fn is_taken(&self) -> bool
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 Error for Error
impl Error for Error
1.30.0 · Source§fn source(&self) -> Option<&(dyn Error + 'static)>
fn source(&self) -> Option<&(dyn Error + 'static)>
1.0.0 · Source§fn description(&self) -> &str
fn description(&self) -> &str
use the Display impl or to_string()
Source§impl IntoResponse for Error
HTML error page. JSON endpoints return ApiError instead.
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.