rpc/natives/forms/
invalid.rs1use 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#[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#[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#[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
59pub 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}