Skip to main content

Error

Enum Error 

Source
#[non_exhaustive]
pub enum Error { Input(Fault), Json(Fault), Host(Fault), Query(Fault), Mutation(Fault), Domain(Fault), Panic(Fault), Other(Fault), }
Expand description

Everything that can go wrong inside an action.

The variant is the coarse triage — where the failure came from — and the Fault inside it is what reaches the platform. Match on the variant when you care where it happened; read Error::code when you care what it was.

It is #[non_exhaustive]: a match on it needs a _ arm, so a variant added later does not break an action that was already written.

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Input(Fault)

The payload the host sent does not match the handler’s input type.

§

Json(Fault)

A JSON document could not be read or written.

§

Host(Fault)

The host could not be asked, or answered with a refusal.

§

Query(Fault)

A GraphQL read failed. Nothing was written.

§

Mutation(Fault)

A GraphQL write failed, and may already have landed.

§

Domain(Fault)

The action decided the request cannot be satisfied.

§

Panic(Fault)

The handler panicked and the panic was turned into this.

§

Other(Fault)

Converted from another error type by ?.

Implementations§

Source§

impl Error

Source

pub fn invalid(message: impl Into<String>) -> Error

The input cannot be accepted as written.

use simpleplatform_sdk::prelude::*;

let error = Error::invalid("'ids' must contain at least one id.")
    .hint("Pass one or more KNOW... ids.");

assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
Examples found in repository?
examples/load_knowledge.rs (lines 161-164)
138fn handler(request: Request<Input>) -> Result<Output, Error> {
139    let ids = wanted_ids(request.data.ids)?;
140
141    let loaded: Loaded =
142        simple::graphql::query(LOAD_KNOWLEDGE, json!({ "ids": ids, "limit": ids.len() }))?;
143
144    let mut found: HashMap<String, Item> = loaded
145        .knowledge
146        .into_iter()
147        .filter_map(|article| {
148            let id = trimmed(&article.id);
149
150            if id.is_empty() {
151                return None;
152            }
153
154            Some((id.clone(), item(id, article)))
155        })
156        .collect();
157
158    let missing: Vec<&String> = ids.iter().filter(|id| !found.contains_key(*id)).collect();
159
160    if !missing.is_empty() {
161        return Err(Error::invalid(format!(
162            "Knowledge article(s) not found: {}.",
163            join(&missing)
164        ))
165        .details(json!({ "missing": missing }))
166        .hint("Search for the article before loading it, or drop the id that does not exist."));
167    }
168
169    Ok(Output {
170        items: ids
171            .iter()
172            .filter_map(|id| found.remove(id))
173            .collect::<Vec<Item>>(),
174    })
175}
176
177/// The ids to load: trimmed, de-duplicated, and every one of them a `KNOW` id.
178fn wanted_ids(requested: Vec<String>) -> Result<Vec<String>, Error> {
179    let mut wanted: Vec<String> = Vec::with_capacity(requested.len());
180    let mut invalid: Vec<String> = Vec::new();
181
182    for id in requested {
183        let id = id.trim().to_string();
184
185        if id.is_empty() {
186            continue;
187        }
188
189        if !id.starts_with("KNOW") {
190            invalid.push(id);
191            continue;
192        }
193
194        if !wanted.contains(&id) {
195            wanted.push(id);
196        }
197    }
198
199    if !invalid.is_empty() {
200        return Err(
201            Error::invalid(format!("Invalid knowledge id(s): {}.", join(&invalid)))
202                .details(json!({ "invalid": invalid }))
203                .hint("A knowledge id begins with KNOW."),
204        );
205    }
206
207    if wanted.is_empty() {
208        return Err(Error::invalid("'ids' must contain at least one KNOW id.")
209            .hint("Pass one or more knowledge record ids."));
210    }
211
212    Ok(wanted)
213}
More examples
Hide additional examples
examples/close_duplicate_lead.rs (line 103)
98fn handler(request: Request<Input>) -> Result<Output, Error> {
99    let duplicate = request.data.lead_id.trim();
100    let survivor = request.data.duplicate_of.trim();
101
102    if duplicate == survivor {
103        return Err(Error::invalid("A lead cannot be a duplicate of itself.")
104            .hint("Pass two different lead ids."));
105    }
106
107    let found: Found = simple::graphql::query(FIND_LEADS, json!({ "ids": [duplicate, survivor] }))?;
108
109    let duplicate_lead = found
110        .leads
111        .iter()
112        .find(|lead| lead.id == duplicate)
113        .ok_or_else(|| {
114            Error::invalid(format!("Lead {duplicate} does not exist."))
115                .details(json!({ "missing": duplicate }))
116                .hint("Search for the lead before closing it.")
117        })?;
118
119    let survivor_lead = found
120        .leads
121        .iter()
122        .find(|lead| lead.id == survivor)
123        .ok_or_else(|| {
124            Error::invalid(format!("Lead {survivor} does not exist."))
125                .details(json!({ "missing": survivor }))
126                .hint("Search for the lead before merging into it.")
127        })?;
128
129    if duplicate_lead.status == "closed" {
130        return Err(Error::domain(
131            "LEAD_ALREADY_CLOSED",
132            format!("Lead {duplicate} is already closed."),
133        )
134        .hint("Nothing to do."));
135    }
136
137    if duplicate_lead.email != survivor_lead.email {
138        return Err(Error::domain(
139            "LEAD_EMAIL_MISMATCH",
140            "The two leads do not share an email address.",
141        )
142        .details(json!({
143            "duplicate": duplicate_lead.email,
144            "survivor": survivor_lead.email,
145        }))
146        .hint("Confirm these are the same person before merging them."));
147    }
148
149    let closed: Closed =
150        simple::graphql::mutate(CLOSE_LEAD, json!({ "id": duplicate, "merged": survivor }))?;
151
152    Ok(Output {
153        closed: duplicate.to_string(),
154        merged_into: survivor.to_string(),
155        rows_changed: closed.result.affected_rows,
156    })
157}
examples/file_expense_receipt.rs (line 111)
106fn handler(request: Request<Input>) -> Result<Output, Error> {
107    let employee = request.data.employee_id.trim();
108    let receipt_url = request.data.receipt_url.trim();
109
110    if employee.is_empty() {
111        return Err(Error::invalid("An expense is filed against an employee.")
112            .hint("Pass the id of the employee the receipt belongs to."));
113    }
114
115    if receipt_url.is_empty() {
116        return Err(Error::invalid("An expense is filed from a receipt.")
117            .hint("Pass the address the receipt is read from."));
118    }
119
120    let policy: Policy = simple::settings::get(APP_ID, &["approval_limit", "currency"])?;
121
122    let receipt = simple::storage::upload_external(
123        Source::url(receipt_url),
124        Target::new(APP_ID, "expense", "receipt"),
125    )?;
126
127    let read: Execution<Receipt> = simple::ai::extract(
128        simple::serde_json::to_value(&receipt)?,
129        "Read the merchant, the currency and the total from this receipt.",
130        json!({
131            "type": "object",
132            "properties": {
133                "merchant": { "type": "string" },
134                "currency": { "type": "string" },
135                "total": { "type": "number" }
136            },
137            "required": ["merchant", "currency", "total"]
138        }),
139        Options::default(),
140    )?;
141
142    let claim = read.data;
143
144    if claim.currency != policy.currency {
145        return Err(Error::domain(
146            "RECEIPT_CURRENCY_MISMATCH",
147            format!(
148                "The receipt is in {} and this app files expenses in {}.",
149                claim.currency, policy.currency
150            ),
151        )
152        .details(json!({ "expected": policy.currency, "receipt": claim.currency }))
153        .hint("File it against an app configured for that currency. The file is stored; the expense is not."));
154    }
155
156    if claim.total > policy.approval_limit {
157        return Err(Error::domain(
158            "EXPENSE_OVER_LIMIT",
159            format!(
160                "{} {} is over the {} approval limit.",
161                claim.total, claim.currency, policy.approval_limit
162            ),
163        )
164        .details(json!({
165            "limit": policy.approval_limit,
166            "merchant": claim.merchant,
167            "total": claim.total,
168        }))
169        .hint("Send it for approval instead. The file is stored; the expense is not."));
170    }
171
172    let filed: Filed = simple::graphql::mutate(
173        FILE_EXPENSE,
174        json!({
175            "employee": employee,
176            "merchant": &claim.merchant,
177            "receipt": &receipt,
178            "total": claim.total,
179        }),
180    )?;
181
182    Ok(Output {
183        expense_id: filed.expense.id,
184        merchant: claim.merchant,
185        total: claim.total,
186        receipt,
187    })
188}
Source

pub fn denied(message: impl Into<String>) -> Error

The current user may not do this. Never retried.

Source

pub fn timed_out(message: impl Into<String>) -> Error

It did not finish in time. Retryable.

Source

pub fn unavailable(message: impl Into<String>) -> Error

Something it depends on is down. Retryable.

Source

pub fn failed(message: impl Into<String>) -> Error

It failed, and there is no more specific account of why.

Source

pub fn domain(code: impl Into<String>, message: impl Into<String>) -> Error

A failure this action names for itself.

The code is carried to the model verbatim and translated generically, which the platform reads as effect unknown. Prefer a canonical code where one fits; reach for this when none does.

use simpleplatform_sdk::prelude::*;

let error = Error::domain("INVOICE_ALREADY_PAID", "This invoice is already paid.");

assert_eq!(error.code().as_str(), "INVOICE_ALREADY_PAID");
Examples found in repository?
examples/close_duplicate_lead.rs (lines 130-133)
98fn handler(request: Request<Input>) -> Result<Output, Error> {
99    let duplicate = request.data.lead_id.trim();
100    let survivor = request.data.duplicate_of.trim();
101
102    if duplicate == survivor {
103        return Err(Error::invalid("A lead cannot be a duplicate of itself.")
104            .hint("Pass two different lead ids."));
105    }
106
107    let found: Found = simple::graphql::query(FIND_LEADS, json!({ "ids": [duplicate, survivor] }))?;
108
109    let duplicate_lead = found
110        .leads
111        .iter()
112        .find(|lead| lead.id == duplicate)
113        .ok_or_else(|| {
114            Error::invalid(format!("Lead {duplicate} does not exist."))
115                .details(json!({ "missing": duplicate }))
116                .hint("Search for the lead before closing it.")
117        })?;
118
119    let survivor_lead = found
120        .leads
121        .iter()
122        .find(|lead| lead.id == survivor)
123        .ok_or_else(|| {
124            Error::invalid(format!("Lead {survivor} does not exist."))
125                .details(json!({ "missing": survivor }))
126                .hint("Search for the lead before merging into it.")
127        })?;
128
129    if duplicate_lead.status == "closed" {
130        return Err(Error::domain(
131            "LEAD_ALREADY_CLOSED",
132            format!("Lead {duplicate} is already closed."),
133        )
134        .hint("Nothing to do."));
135    }
136
137    if duplicate_lead.email != survivor_lead.email {
138        return Err(Error::domain(
139            "LEAD_EMAIL_MISMATCH",
140            "The two leads do not share an email address.",
141        )
142        .details(json!({
143            "duplicate": duplicate_lead.email,
144            "survivor": survivor_lead.email,
145        }))
146        .hint("Confirm these are the same person before merging them."));
147    }
148
149    let closed: Closed =
150        simple::graphql::mutate(CLOSE_LEAD, json!({ "id": duplicate, "merged": survivor }))?;
151
152    Ok(Output {
153        closed: duplicate.to_string(),
154        merged_into: survivor.to_string(),
155        rows_changed: closed.result.affected_rows,
156    })
157}
More examples
Hide additional examples
examples/file_expense_receipt.rs (lines 145-151)
106fn handler(request: Request<Input>) -> Result<Output, Error> {
107    let employee = request.data.employee_id.trim();
108    let receipt_url = request.data.receipt_url.trim();
109
110    if employee.is_empty() {
111        return Err(Error::invalid("An expense is filed against an employee.")
112            .hint("Pass the id of the employee the receipt belongs to."));
113    }
114
115    if receipt_url.is_empty() {
116        return Err(Error::invalid("An expense is filed from a receipt.")
117            .hint("Pass the address the receipt is read from."));
118    }
119
120    let policy: Policy = simple::settings::get(APP_ID, &["approval_limit", "currency"])?;
121
122    let receipt = simple::storage::upload_external(
123        Source::url(receipt_url),
124        Target::new(APP_ID, "expense", "receipt"),
125    )?;
126
127    let read: Execution<Receipt> = simple::ai::extract(
128        simple::serde_json::to_value(&receipt)?,
129        "Read the merchant, the currency and the total from this receipt.",
130        json!({
131            "type": "object",
132            "properties": {
133                "merchant": { "type": "string" },
134                "currency": { "type": "string" },
135                "total": { "type": "number" }
136            },
137            "required": ["merchant", "currency", "total"]
138        }),
139        Options::default(),
140    )?;
141
142    let claim = read.data;
143
144    if claim.currency != policy.currency {
145        return Err(Error::domain(
146            "RECEIPT_CURRENCY_MISMATCH",
147            format!(
148                "The receipt is in {} and this app files expenses in {}.",
149                claim.currency, policy.currency
150            ),
151        )
152        .details(json!({ "expected": policy.currency, "receipt": claim.currency }))
153        .hint("File it against an app configured for that currency. The file is stored; the expense is not."));
154    }
155
156    if claim.total > policy.approval_limit {
157        return Err(Error::domain(
158            "EXPENSE_OVER_LIMIT",
159            format!(
160                "{} {} is over the {} approval limit.",
161                claim.total, claim.currency, policy.approval_limit
162            ),
163        )
164        .details(json!({
165            "limit": policy.approval_limit,
166            "merchant": claim.merchant,
167            "total": claim.total,
168        }))
169        .hint("Send it for approval instead. The file is stored; the expense is not."));
170    }
171
172    let filed: Filed = simple::graphql::mutate(
173        FILE_EXPENSE,
174        json!({
175            "employee": employee,
176            "merchant": &claim.merchant,
177            "receipt": &receipt,
178            "total": claim.total,
179        }),
180    )?;
181
182    Ok(Output {
183        expense_id: filed.expense.id,
184        merchant: claim.merchant,
185        total: claim.total,
186        receipt,
187    })
188}
Source

pub fn other(cause: impl Display) -> Error

Anything that is not one of ours, kept for its message.

Source

pub fn hint(self, hint: impl Into<String>) -> Error

What to do about it. This reaches the model; spend it on the repair.

Examples found in repository?
examples/load_knowledge.rs (line 166)
138fn handler(request: Request<Input>) -> Result<Output, Error> {
139    let ids = wanted_ids(request.data.ids)?;
140
141    let loaded: Loaded =
142        simple::graphql::query(LOAD_KNOWLEDGE, json!({ "ids": ids, "limit": ids.len() }))?;
143
144    let mut found: HashMap<String, Item> = loaded
145        .knowledge
146        .into_iter()
147        .filter_map(|article| {
148            let id = trimmed(&article.id);
149
150            if id.is_empty() {
151                return None;
152            }
153
154            Some((id.clone(), item(id, article)))
155        })
156        .collect();
157
158    let missing: Vec<&String> = ids.iter().filter(|id| !found.contains_key(*id)).collect();
159
160    if !missing.is_empty() {
161        return Err(Error::invalid(format!(
162            "Knowledge article(s) not found: {}.",
163            join(&missing)
164        ))
165        .details(json!({ "missing": missing }))
166        .hint("Search for the article before loading it, or drop the id that does not exist."));
167    }
168
169    Ok(Output {
170        items: ids
171            .iter()
172            .filter_map(|id| found.remove(id))
173            .collect::<Vec<Item>>(),
174    })
175}
176
177/// The ids to load: trimmed, de-duplicated, and every one of them a `KNOW` id.
178fn wanted_ids(requested: Vec<String>) -> Result<Vec<String>, Error> {
179    let mut wanted: Vec<String> = Vec::with_capacity(requested.len());
180    let mut invalid: Vec<String> = Vec::new();
181
182    for id in requested {
183        let id = id.trim().to_string();
184
185        if id.is_empty() {
186            continue;
187        }
188
189        if !id.starts_with("KNOW") {
190            invalid.push(id);
191            continue;
192        }
193
194        if !wanted.contains(&id) {
195            wanted.push(id);
196        }
197    }
198
199    if !invalid.is_empty() {
200        return Err(
201            Error::invalid(format!("Invalid knowledge id(s): {}.", join(&invalid)))
202                .details(json!({ "invalid": invalid }))
203                .hint("A knowledge id begins with KNOW."),
204        );
205    }
206
207    if wanted.is_empty() {
208        return Err(Error::invalid("'ids' must contain at least one KNOW id.")
209            .hint("Pass one or more knowledge record ids."));
210    }
211
212    Ok(wanted)
213}
More examples
Hide additional examples
examples/close_duplicate_lead.rs (line 104)
98fn handler(request: Request<Input>) -> Result<Output, Error> {
99    let duplicate = request.data.lead_id.trim();
100    let survivor = request.data.duplicate_of.trim();
101
102    if duplicate == survivor {
103        return Err(Error::invalid("A lead cannot be a duplicate of itself.")
104            .hint("Pass two different lead ids."));
105    }
106
107    let found: Found = simple::graphql::query(FIND_LEADS, json!({ "ids": [duplicate, survivor] }))?;
108
109    let duplicate_lead = found
110        .leads
111        .iter()
112        .find(|lead| lead.id == duplicate)
113        .ok_or_else(|| {
114            Error::invalid(format!("Lead {duplicate} does not exist."))
115                .details(json!({ "missing": duplicate }))
116                .hint("Search for the lead before closing it.")
117        })?;
118
119    let survivor_lead = found
120        .leads
121        .iter()
122        .find(|lead| lead.id == survivor)
123        .ok_or_else(|| {
124            Error::invalid(format!("Lead {survivor} does not exist."))
125                .details(json!({ "missing": survivor }))
126                .hint("Search for the lead before merging into it.")
127        })?;
128
129    if duplicate_lead.status == "closed" {
130        return Err(Error::domain(
131            "LEAD_ALREADY_CLOSED",
132            format!("Lead {duplicate} is already closed."),
133        )
134        .hint("Nothing to do."));
135    }
136
137    if duplicate_lead.email != survivor_lead.email {
138        return Err(Error::domain(
139            "LEAD_EMAIL_MISMATCH",
140            "The two leads do not share an email address.",
141        )
142        .details(json!({
143            "duplicate": duplicate_lead.email,
144            "survivor": survivor_lead.email,
145        }))
146        .hint("Confirm these are the same person before merging them."));
147    }
148
149    let closed: Closed =
150        simple::graphql::mutate(CLOSE_LEAD, json!({ "id": duplicate, "merged": survivor }))?;
151
152    Ok(Output {
153        closed: duplicate.to_string(),
154        merged_into: survivor.to_string(),
155        rows_changed: closed.result.affected_rows,
156    })
157}
examples/file_expense_receipt.rs (line 112)
106fn handler(request: Request<Input>) -> Result<Output, Error> {
107    let employee = request.data.employee_id.trim();
108    let receipt_url = request.data.receipt_url.trim();
109
110    if employee.is_empty() {
111        return Err(Error::invalid("An expense is filed against an employee.")
112            .hint("Pass the id of the employee the receipt belongs to."));
113    }
114
115    if receipt_url.is_empty() {
116        return Err(Error::invalid("An expense is filed from a receipt.")
117            .hint("Pass the address the receipt is read from."));
118    }
119
120    let policy: Policy = simple::settings::get(APP_ID, &["approval_limit", "currency"])?;
121
122    let receipt = simple::storage::upload_external(
123        Source::url(receipt_url),
124        Target::new(APP_ID, "expense", "receipt"),
125    )?;
126
127    let read: Execution<Receipt> = simple::ai::extract(
128        simple::serde_json::to_value(&receipt)?,
129        "Read the merchant, the currency and the total from this receipt.",
130        json!({
131            "type": "object",
132            "properties": {
133                "merchant": { "type": "string" },
134                "currency": { "type": "string" },
135                "total": { "type": "number" }
136            },
137            "required": ["merchant", "currency", "total"]
138        }),
139        Options::default(),
140    )?;
141
142    let claim = read.data;
143
144    if claim.currency != policy.currency {
145        return Err(Error::domain(
146            "RECEIPT_CURRENCY_MISMATCH",
147            format!(
148                "The receipt is in {} and this app files expenses in {}.",
149                claim.currency, policy.currency
150            ),
151        )
152        .details(json!({ "expected": policy.currency, "receipt": claim.currency }))
153        .hint("File it against an app configured for that currency. The file is stored; the expense is not."));
154    }
155
156    if claim.total > policy.approval_limit {
157        return Err(Error::domain(
158            "EXPENSE_OVER_LIMIT",
159            format!(
160                "{} {} is over the {} approval limit.",
161                claim.total, claim.currency, policy.approval_limit
162            ),
163        )
164        .details(json!({
165            "limit": policy.approval_limit,
166            "merchant": claim.merchant,
167            "total": claim.total,
168        }))
169        .hint("Send it for approval instead. The file is stored; the expense is not."));
170    }
171
172    let filed: Filed = simple::graphql::mutate(
173        FILE_EXPENSE,
174        json!({
175            "employee": employee,
176            "merchant": &claim.merchant,
177            "receipt": &receipt,
178            "total": claim.total,
179        }),
180    )?;
181
182    Ok(Output {
183        expense_id: filed.expense.id,
184        merchant: claim.merchant,
185        total: claim.total,
186        receipt,
187    })
188}
Source

pub fn details(self, details: Value) -> Error

Structured evidence beside the message.

details is always a JSON object on the wire, so a value that is not one is wrapped in one under detail and the failure travels whole — code, category, message and hint together with the evidence.

Examples found in repository?
examples/load_knowledge.rs (line 165)
138fn handler(request: Request<Input>) -> Result<Output, Error> {
139    let ids = wanted_ids(request.data.ids)?;
140
141    let loaded: Loaded =
142        simple::graphql::query(LOAD_KNOWLEDGE, json!({ "ids": ids, "limit": ids.len() }))?;
143
144    let mut found: HashMap<String, Item> = loaded
145        .knowledge
146        .into_iter()
147        .filter_map(|article| {
148            let id = trimmed(&article.id);
149
150            if id.is_empty() {
151                return None;
152            }
153
154            Some((id.clone(), item(id, article)))
155        })
156        .collect();
157
158    let missing: Vec<&String> = ids.iter().filter(|id| !found.contains_key(*id)).collect();
159
160    if !missing.is_empty() {
161        return Err(Error::invalid(format!(
162            "Knowledge article(s) not found: {}.",
163            join(&missing)
164        ))
165        .details(json!({ "missing": missing }))
166        .hint("Search for the article before loading it, or drop the id that does not exist."));
167    }
168
169    Ok(Output {
170        items: ids
171            .iter()
172            .filter_map(|id| found.remove(id))
173            .collect::<Vec<Item>>(),
174    })
175}
176
177/// The ids to load: trimmed, de-duplicated, and every one of them a `KNOW` id.
178fn wanted_ids(requested: Vec<String>) -> Result<Vec<String>, Error> {
179    let mut wanted: Vec<String> = Vec::with_capacity(requested.len());
180    let mut invalid: Vec<String> = Vec::new();
181
182    for id in requested {
183        let id = id.trim().to_string();
184
185        if id.is_empty() {
186            continue;
187        }
188
189        if !id.starts_with("KNOW") {
190            invalid.push(id);
191            continue;
192        }
193
194        if !wanted.contains(&id) {
195            wanted.push(id);
196        }
197    }
198
199    if !invalid.is_empty() {
200        return Err(
201            Error::invalid(format!("Invalid knowledge id(s): {}.", join(&invalid)))
202                .details(json!({ "invalid": invalid }))
203                .hint("A knowledge id begins with KNOW."),
204        );
205    }
206
207    if wanted.is_empty() {
208        return Err(Error::invalid("'ids' must contain at least one KNOW id.")
209            .hint("Pass one or more knowledge record ids."));
210    }
211
212    Ok(wanted)
213}
More examples
Hide additional examples
examples/close_duplicate_lead.rs (line 115)
98fn handler(request: Request<Input>) -> Result<Output, Error> {
99    let duplicate = request.data.lead_id.trim();
100    let survivor = request.data.duplicate_of.trim();
101
102    if duplicate == survivor {
103        return Err(Error::invalid("A lead cannot be a duplicate of itself.")
104            .hint("Pass two different lead ids."));
105    }
106
107    let found: Found = simple::graphql::query(FIND_LEADS, json!({ "ids": [duplicate, survivor] }))?;
108
109    let duplicate_lead = found
110        .leads
111        .iter()
112        .find(|lead| lead.id == duplicate)
113        .ok_or_else(|| {
114            Error::invalid(format!("Lead {duplicate} does not exist."))
115                .details(json!({ "missing": duplicate }))
116                .hint("Search for the lead before closing it.")
117        })?;
118
119    let survivor_lead = found
120        .leads
121        .iter()
122        .find(|lead| lead.id == survivor)
123        .ok_or_else(|| {
124            Error::invalid(format!("Lead {survivor} does not exist."))
125                .details(json!({ "missing": survivor }))
126                .hint("Search for the lead before merging into it.")
127        })?;
128
129    if duplicate_lead.status == "closed" {
130        return Err(Error::domain(
131            "LEAD_ALREADY_CLOSED",
132            format!("Lead {duplicate} is already closed."),
133        )
134        .hint("Nothing to do."));
135    }
136
137    if duplicate_lead.email != survivor_lead.email {
138        return Err(Error::domain(
139            "LEAD_EMAIL_MISMATCH",
140            "The two leads do not share an email address.",
141        )
142        .details(json!({
143            "duplicate": duplicate_lead.email,
144            "survivor": survivor_lead.email,
145        }))
146        .hint("Confirm these are the same person before merging them."));
147    }
148
149    let closed: Closed =
150        simple::graphql::mutate(CLOSE_LEAD, json!({ "id": duplicate, "merged": survivor }))?;
151
152    Ok(Output {
153        closed: duplicate.to_string(),
154        merged_into: survivor.to_string(),
155        rows_changed: closed.result.affected_rows,
156    })
157}
examples/file_expense_receipt.rs (line 152)
106fn handler(request: Request<Input>) -> Result<Output, Error> {
107    let employee = request.data.employee_id.trim();
108    let receipt_url = request.data.receipt_url.trim();
109
110    if employee.is_empty() {
111        return Err(Error::invalid("An expense is filed against an employee.")
112            .hint("Pass the id of the employee the receipt belongs to."));
113    }
114
115    if receipt_url.is_empty() {
116        return Err(Error::invalid("An expense is filed from a receipt.")
117            .hint("Pass the address the receipt is read from."));
118    }
119
120    let policy: Policy = simple::settings::get(APP_ID, &["approval_limit", "currency"])?;
121
122    let receipt = simple::storage::upload_external(
123        Source::url(receipt_url),
124        Target::new(APP_ID, "expense", "receipt"),
125    )?;
126
127    let read: Execution<Receipt> = simple::ai::extract(
128        simple::serde_json::to_value(&receipt)?,
129        "Read the merchant, the currency and the total from this receipt.",
130        json!({
131            "type": "object",
132            "properties": {
133                "merchant": { "type": "string" },
134                "currency": { "type": "string" },
135                "total": { "type": "number" }
136            },
137            "required": ["merchant", "currency", "total"]
138        }),
139        Options::default(),
140    )?;
141
142    let claim = read.data;
143
144    if claim.currency != policy.currency {
145        return Err(Error::domain(
146            "RECEIPT_CURRENCY_MISMATCH",
147            format!(
148                "The receipt is in {} and this app files expenses in {}.",
149                claim.currency, policy.currency
150            ),
151        )
152        .details(json!({ "expected": policy.currency, "receipt": claim.currency }))
153        .hint("File it against an app configured for that currency. The file is stored; the expense is not."));
154    }
155
156    if claim.total > policy.approval_limit {
157        return Err(Error::domain(
158            "EXPENSE_OVER_LIMIT",
159            format!(
160                "{} {} is over the {} approval limit.",
161                claim.total, claim.currency, policy.approval_limit
162            ),
163        )
164        .details(json!({
165            "limit": policy.approval_limit,
166            "merchant": claim.merchant,
167            "total": claim.total,
168        }))
169        .hint("Send it for approval instead. The file is stored; the expense is not."));
170    }
171
172    let filed: Filed = simple::graphql::mutate(
173        FILE_EXPENSE,
174        json!({
175            "employee": employee,
176            "merchant": &claim.merchant,
177            "receipt": &receipt,
178            "total": claim.total,
179        }),
180    )?;
181
182    Ok(Output {
183        expense_id: filed.expense.id,
184        merchant: claim.merchant,
185        total: claim.total,
186        receipt,
187    })
188}
Source

pub fn code_of(self, code: Code) -> Error

File this failure under a different code, taking that code’s category and retryability with it.

Source

pub fn category_of(self, category: Category) -> Error

Report this failure under a different category, leaving the code alone.

Source

pub fn retryable(self, retryable: bool) -> Error

Narrow the retryability verdict.

It can only be narrowed: a code that is not retryable stays that way, so an action cannot talk the platform into repeating a write.

Source

pub fn fault(&self) -> &Fault

Everything this failure carries onto the wire.

Source

pub fn code(&self) -> &Code

The code this failure is filed under.

Source

pub fn category(&self) -> Category

The class this failure is reported under.

Source

pub fn message(&self) -> &str

The sentence the model is shown.

Source

pub fn is_retryable(&self) -> bool

Whether repeating an identical call could plausibly succeed.

Source

pub fn body(&self) -> Value

The canonical failure body, exactly as the platform reads it.

Returning this from a handler instead of returning Err is what an action does when a failure is a result rather than a fault — the call worked, and the answer is that it cannot be satisfied.

Trait Implementations§

Source§

impl Clone for Error

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Error

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Error

Source§

fn fmt(&self, formatter: &mut Formatter<'_>) -> Result

The actionable sentence, and nothing else.

This is the string that travels within the 1000-byte budget and that the model reads, so it carries no Debug decoration, no variant name and no code prefix. All of those are available from the accessors, and the budget is spent on what whoever reads it has to act on.

Source§

impl<E> From<E> for Error
where E: Error + 'static,

Everything ? can reach, in one impl.

This is why Error does not implement std::error::Error: the standard library’s reflexive impl<T> From<T> for T would overlap with this one the moment it did.

Source§

fn from(cause: E) -> Error

Converts to this type from the input type.

Auto Trait Implementations§

§

impl Freeze for Error

§

impl RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl UnsafeUnpin for Error

§

impl UnwindSafe for Error

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.