#[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
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
impl Error
Sourcepub fn invalid(message: impl Into<String>) -> Error
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?
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
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}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}Sourcepub fn denied(message: impl Into<String>) -> Error
pub fn denied(message: impl Into<String>) -> Error
The current user may not do this. Never retried.
Something it depends on is down. Retryable.
Sourcepub fn failed(message: impl Into<String>) -> Error
pub fn failed(message: impl Into<String>) -> Error
It failed, and there is no more specific account of why.
Sourcepub fn domain(code: impl Into<String>, message: impl Into<String>) -> Error
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?
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
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}Sourcepub fn other(cause: impl Display) -> Error
pub fn other(cause: impl Display) -> Error
Anything that is not one of ours, kept for its message.
Sourcepub fn hint(self, hint: impl Into<String>) -> Error
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?
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
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}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}Sourcepub fn details(self, details: Value) -> Error
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?
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
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}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}Sourcepub fn code_of(self, code: Code) -> Error
pub fn code_of(self, code: Code) -> Error
File this failure under a different code, taking that code’s category and retryability with it.
Sourcepub fn category_of(self, category: Category) -> Error
pub fn category_of(self, category: Category) -> Error
Report this failure under a different category, leaving the code alone.
Sourcepub fn retryable(self, retryable: bool) -> Error
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.
Sourcepub fn is_retryable(&self) -> bool
pub fn is_retryable(&self) -> bool
Whether repeating an identical call could plausibly succeed.
Trait Implementations§
Source§impl Display for Error
impl Display for Error
Source§fn fmt(&self, formatter: &mut Formatter<'_>) -> Result
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.