Skip to Content

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.

VariantStatusThe caller sees
BadRequest(m)400m
Unauthorized(m)401m
Forbidden(m)403m
NotFound(m)404m
Conflict(m)409m
Floor(m)502m
Internal(e)500internal error; the backend logs e with its causes
Device(r)401 or 403why 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:

StatusWhen
404no route on this path ("no such route")
405a route on this path, but not this method; the Allow header lists the methods
413the body is over the route's limit, before it's read
504the handler ran past the route's timeout and was stopped
500the 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>) -> Self

For 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) -> u16

The 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:

FromBecomes
sqlx::Error::RowNotFound (from fetch_one)NotFound("not found"), 404
a unique violationConflict("that already exists"), 409
a foreign key violationConflict("that refers to something that isn't there"), 409
any other sqlx::ErrorInternal, 500
serde_json::ErrorInternal, 500
anyhow::ErrorInternal, 500
an error from the link to FloorFloor, 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 there

To 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. For Internal, the message includes its causes.
  • A job whose handler returns Err fails, and its queue retries it with backoff. job.attempt says 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> or Job<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.

On this page