Errors
floor::Error and floor::Result: each variant and its HTTP status, OrNotFound, how sqlx and serde errors convert, and what an error does in a trigger.
Handlers return floor::Result. Each error is a status code and a message. A route answers with
the status and a JSON body:
{ "error": "lane 3 doesn't exist" }Result
pub type Result<T, E = Error> = std::result::Result<T, E>;Error
#[derive(Debug)]
pub enum Error {
/// 400: the request's fault, with what's wrong.
BadRequest(String),
/// 401: no valid token.
Unauthorized(String),
/// 403: signed in, not allowed.
Forbidden(String),
/// 404
NotFound(String),
/// 409: a conflict with what's there (a duplicate, a state that doesn't allow it).
Conflict(String),
/// 502: Floor refused or failed a call (a device command, a publish, …).
Floor(String),
/// 500: a bug or an outage; logged, and the caller sees only "internal error".
Internal(anyhow::Error),
/// A device's token request refused (`cx.device_token`): 401 or 403.
Device(DeviceRefusal),
}
pub enum DeviceRefusal {
Unauthorized, // 401: a bad, expired or misaddressed assertion, or a device Floor doesn't know
Pending, // 403: claimed, waiting for an approval
Revoked, // 403: revoked; it must claim again
}Error implements std::error::Error and Display; Display is the message. It also
implements IntoResponse, so a handler may return it directly.
| Variant | Status | The caller sees |
|---|---|---|
BadRequest(m) | 400 | m |
Unauthorized(m) | 401 | m |
Forbidden(m) | 403 | m |
NotFound(m) | 404 | m |
Conflict(m) | 409 | m |
Floor(m) | 502 | m |
Internal(e) | 500 | internal error; the backend logs e with its causes |
Device(r) | 401 or 403 | why the device gets no token |
What a Cx call returns when Floor refuses it: Floor's own answer, so ? passes it on with
the right status. Approving a device that isn't pending is a Conflict (409); a device, camera
or person Floor doesn't know is a NotFound (404); a bad request is a BadRequest (400); not
allowed is a Forbidden (403). Only Floor failing or being unreachable is a Floor (502).
Other statuses come from the framework, not from Error:
| Status | When |
|---|---|
| 404 | no route on this path ("no such route") |
| 405 | a route on this path, but not this method; the Allow header lists the methods |
| 413 | the body is over the route's limit, before it's read |
| 504 | the handler ran past the route's timeout and was stopped |
| 500 | the handler panicked; the backend keeps running |
Constructors
pub fn bad_request(m: impl Into<String>) -> Self
pub fn unauthorized(m: impl Into<String>) -> Self
pub fn forbidden(m: impl Into<String>) -> Self
pub fn not_found(m: impl Into<String>) -> Self
pub fn conflict(m: impl Into<String>) -> SelfFor the others, write the variant: Error::Floor(…), Error::Internal(e.into()).
if device != msg.device {
return Err(Error::bad_request(format!("lane {} isn't on {}", e.lane_id, msg.device)));
}error.status
pub fn status(&self) -> u16The HTTP status the error answers with.
OrNotFound
pub trait OrNotFound<T> {
fn or_not_found(self) -> Result<T>;
}
impl<T> OrNotFound<T> for Option<T> { … }Turns None into Error::NotFound("not found"), for a row that may be missing:
let visit: Visit = sqlx::query_as("select … from visits where id = $1 and organization = $2")
.bind(id)
.bind(cx.org()?)
.fetch_optional(cx.db())
.await?
.or_not_found()?;It's in the prelude.
Conversions
? converts these into Error:
| From | Becomes |
|---|---|
sqlx::Error::RowNotFound (from fetch_one) | NotFound("not found"), 404 |
| a unique violation | Conflict("that already exists"), 409 |
| a foreign key violation | Conflict("that refers to something that isn't there"), 409 |
any other sqlx::Error | Internal, 500 |
serde_json::Error | Internal, 500 |
anyhow::Error | Internal, 500 |
| an error from the link to Floor | Floor, 502 |
A unique index is enough to answer a duplicate with a 409:
sqlx::query("insert into vehicles (organization, plate) values ($1, $2)")
.bind(cx.org()?)
.bind(&v.plate)
.execute(cx.db())
.await?; // 409 "that already exists" when the plate is thereTo say more, match the error yourself before ?.
Extractors answer with 400 on their own: a missing or wrong JSON body, a query string or a path
parameter that doesn't fit. The caller methods on Cx answer with 401 or 403. See
Cx.
In a trigger
A trigger handler (#[mqtt], #[every], #[cron], #[job], #[device]) returns Result<()>:
Ok(())acks the trigger.Err(e)acks it with the error's message. The backend logs it, and Floor logs and counts it. ForInternal, the message includes its causes.- A job whose handler returns
Errfails, and its queue retries it with backoff.job.attemptsays which attempt this is. A cron run is a job too, so a failed run is retried the same way. - An MQTT message, a tick or a device event isn't sent again for an error: the error is the end of it.
- An input that can't be read, such as a payload that doesn't fit
Mqtt<T>orJob<T>, is an error before the handler runs. For a job, that means it's retried like any other failure. - A panic is an error too ("the handler panicked"); the backend keeps running.
Delivery is at least once: a trigger whose ack never reached Floor, because the backend stopped or the link broke, comes again. A handler that changes data should notice an event it has already seen:
#[mqtt("+/events")]
pub async fn events(cx: Cx, msg: Mqtt<PlateEvent>) -> Result<()> {
let seen: Option<String> =
sqlx::query_scalar("select action from edge_events where event_id = $1")
.bind(&msg.body.event_id)
.fetch_optional(cx.db())
.await?;
if seen.is_some() {
return Ok(());
}
// …
Ok(())
}A #[background] task that returns Err is logged. The backend doesn't start it again, so a
task that should outlive an error handles it inside its loop.
In a WebSocket
A #[ws] handler returns Result<()> too. A handler that takes a Socket runs after the
upgrade, so an Err doesn't reach the caller as a status: the backend logs it and the socket
closes. One that takes an Upgrade answers with its Err as an ordinary HTTP status, if it
returns before up.accept() (WebSockets). socket.recv_json
gives a BadRequest for a message that isn't the type; sending on a socket the caller left
gives an Internal.