Lines
100 %
Functions
91.18 %
Branches
//! The native errors of the client forms: the `form-invalid` condition with
//! its field errors as a readable plist list, and every other [`Failure`].
use forms::FieldError;
use scripting::runtime::{EvalValue, HostCondition};
use crate::envelope::ErrorCode;
use crate::forms::outcome::key;
use crate::forms::{Failure, FormAction, count_result};
use crate::host_failure::not_found_condition;
fn detail(errors: &[FieldError]) -> EvalValue {
let field_error = |error: &FieldError| {
EvalValue::List(vec![
key("FIELD"),
EvalValue::String(error.field.clone()),
key("MESSAGE"),
EvalValue::String(error.message.clone()),
])
};
EvalValue::List(errors.iter().map(field_error).collect())
}
/// The error a submit returns when its values are invalid.
#[must_use]
pub fn form_invalid(errors: &[FieldError]) -> wasmtime::Error {
wasmtime::Error::new(HostCondition {
code: ErrorCode::FORM_INVALID.to_string(),
message: match errors.len() {
1 => "1 field invalid".to_string(),
n => format!("{n} fields invalid"),
},
detail: Some(detail(errors)),
})
/// A bad native argument: unknown form name or option source.
pub fn args_error(message: impl Into<String>) -> wasmtime::Error {
code: ErrorCode::ARGS.to_string(),
message: message.into(),
detail: None,
/// The native error: `form-invalid` for field errors, the original error for
/// an internal failure, `not-found` for a missing entity, `args` for every other cause.
pub fn native_failure(failure: Failure) -> wasmtime::Error {
match failure {
Failure::Invalid(errors) => form_invalid(&errors),
Failure::Internal(err) => err,
missing @ Failure::Missing(_) => not_found_condition(missing.to_string(), None),
other => args_error(other.to_string()),
/// Counts `result` as one request of `form`, then maps its failure to the native error.
pub fn counted<T>(
form: &str,
action: FormAction,
result: Result<T, Failure>,
) -> wasmtime::Result<T> {
count_result(form, action, result).map_err(native_failure)