Skip to main content

rpc/natives/forms/
invalid.rs

1//! The native errors of the client forms: the `form-invalid` condition with
2//! its field errors as a readable plist list, and every other [`Failure`].
3
4use forms::FieldError;
5use scripting::runtime::{EvalValue, HostCondition};
6
7use crate::envelope::ErrorCode;
8use crate::forms::outcome::key;
9use crate::forms::{Failure, FormAction, count_result};
10use crate::host_failure::not_found_condition;
11
12fn detail(errors: &[FieldError]) -> EvalValue {
13    let field_error = |error: &FieldError| {
14        EvalValue::List(vec![
15            key("FIELD"),
16            EvalValue::String(error.field.clone()),
17            key("MESSAGE"),
18            EvalValue::String(error.message.clone()),
19        ])
20    };
21    EvalValue::List(errors.iter().map(field_error).collect())
22}
23
24/// The error a submit returns when its values are invalid.
25#[must_use]
26pub fn form_invalid(errors: &[FieldError]) -> wasmtime::Error {
27    wasmtime::Error::new(HostCondition {
28        code: ErrorCode::FORM_INVALID.to_string(),
29        message: match errors.len() {
30            1 => "1 field invalid".to_string(),
31            n => format!("{n} fields invalid"),
32        },
33        detail: Some(detail(errors)),
34    })
35}
36
37/// A bad native argument: unknown form name or option source.
38#[must_use]
39pub fn args_error(message: impl Into<String>) -> wasmtime::Error {
40    wasmtime::Error::new(HostCondition {
41        code: ErrorCode::ARGS.to_string(),
42        message: message.into(),
43        detail: None,
44    })
45}
46
47/// The native error: `form-invalid` for field errors, the original error for
48/// an internal failure, `not-found` for a missing entity, `args` for every other cause.
49#[must_use]
50pub fn native_failure(failure: Failure) -> wasmtime::Error {
51    match failure {
52        Failure::Invalid(errors) => form_invalid(&errors),
53        Failure::Internal(err) => err,
54        missing @ Failure::Missing(_) => not_found_condition(missing.to_string(), None),
55        other => args_error(other.to_string()),
56    }
57}
58
59/// Counts `result` as one request of `form`, then maps its failure to the native error.
60pub fn counted<T>(
61    form: &str,
62    action: FormAction,
63    result: Result<T, Failure>,
64) -> wasmtime::Result<T> {
65    count_result(form, action, result).map_err(native_failure)
66}