Struct mailpot::Error

source ·
pub struct Error(pub ErrorKind, _);
Expand description

The Error type.

This tuple struct is made of two elements:

  • an ErrorKind which is used to determine the type of the error.
  • An internal State, not meant for direct use outside of error_chain internals, containing:
    • a backtrace, generated when the error is created.
    • an error chain, used for the implementation of Error::cause().

Tuple Fields§

§0: ErrorKind

The kind of the error.

Implementations§

source§

impl Error

source

pub fn from_kind(kind: ErrorKind) -> Error

Constructs an error from a kind, and generates a backtrace.

source

pub fn with_chain<E, K>(error: E, kind: K) -> Errorwhere E: Error + Send + 'static, K: Into<ErrorKind>,

Constructs a chained error from another error and a kind, and generates a backtrace.

source

pub fn with_boxed_chain<K>(error: Box<dyn Error + Send>, kind: K) -> Errorwhere K: Into<ErrorKind>,

Construct a chained error from another boxed error and a kind, and generates a backtrace

source

pub fn kind(&self) -> &ErrorKind

Returns the kind of the error.

source

pub fn iter(&self) -> Iter<'_>

Iterates over the error chain.

source

pub fn backtrace(&self) -> Option<&Backtrace>

Returns the backtrace associated with this error.

source

pub fn chain_err<F, EK>(self, error: F) -> Errorwhere F: FnOnce() -> EK, EK: Into<ErrorKind>,

Extends the error chain with a new entry.

Examples found in repository?
core/src/connection.rs (line 617)
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
    pub fn remove_list_owner(&self, list_pk: i64, owner_pk: i64) -> Result<()> {
        self.connection
            .query_row(
                "DELETE FROM owner WHERE list = ? AND pk = ? RETURNING *;",
                rusqlite::params![&list_pk, &owner_pk],
                |_| Ok(()),
            )
            .map_err(|err| {
                if matches!(err, rusqlite::Error::QueryReturnedNoRows) {
                    Error::from(err).chain_err(|| NotFound("list or list owner not found!"))
                } else {
                    err.into()
                }
            })?;
        Ok(())
    }

    /// Add an owner of a mailing list.
    pub fn add_list_owner(&self, list_owner: ListOwner) -> Result<DbVal<ListOwner>> {
        let mut stmt = self.connection.prepare(
            "INSERT OR REPLACE INTO owner(list, address, name) VALUES (?, ?, ?) RETURNING *;",
        )?;
        let list_pk = list_owner.list;
        let ret = stmt
            .query_row(
                rusqlite::params![&list_pk, &list_owner.address, &list_owner.name,],
                |row| {
                    let pk = row.get("pk")?;
                    Ok(DbVal(
                        ListOwner {
                            pk,
                            list: row.get("list")?,
                            address: row.get("address")?,
                            name: row.get("name")?,
                        },
                        pk,
                    ))
                },
            )
            .map_err(|err| {
                if matches!(
                    err,
                    rusqlite::Error::SqliteFailure(
                        rusqlite::ffi::Error {
                            code: rusqlite::ffi::ErrorCode::ConstraintViolation,
                            extended_code: 787
                        },
                        _
                    )
                ) {
                    Error::from(err).chain_err(|| NotFound("Could not find a list with this pk."))
                } else {
                    err.into()
                }
            })?;

        trace!("add_list_owner {:?}.", &ret);
        Ok(ret)
    }
More examples
Hide additional examples
core/src/policies.rs (line 139)
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
        pub fn remove_list_post_policy(&self, list_pk: i64, policy_pk: i64) -> Result<()> {
            let mut stmt = self
                .connection
                .prepare("DELETE FROM post_policy WHERE pk = ? AND list = ? RETURNING *;")?;
            stmt.query_row(rusqlite::params![&policy_pk, &list_pk,], |_| Ok(()))
                .map_err(|err| {
                    if matches!(err, rusqlite::Error::QueryReturnedNoRows) {
                        Error::from(err).chain_err(|| NotFound("list or list policy not found!"))
                    } else {
                        err.into()
                    }
                })?;

            trace!("remove_list_post_policy {} {}.", list_pk, policy_pk);
            Ok(())
        }

        /// Set the unique post policy for a list.
        pub fn set_list_post_policy(&self, policy: PostPolicy) -> Result<DbVal<PostPolicy>> {
            if !(policy.announce_only
                || policy.subscription_only
                || policy.approval_needed
                || policy.open
                || policy.custom)
            {
                return Err(
                    "Cannot add empty policy. Having no policies is probably what you want to do."
                        .into(),
                );
            }
            let list_pk = policy.list;

            let mut stmt = self.connection.prepare(
                "INSERT OR REPLACE INTO post_policy(list, announce_only, subscription_only, \
                 approval_needed, open, custom) VALUES (?, ?, ?, ?, ?, ?) RETURNING *;",
            )?;
            let ret = stmt
                .query_row(
                    rusqlite::params![
                        &list_pk,
                        &policy.announce_only,
                        &policy.subscription_only,
                        &policy.approval_needed,
                        &policy.open,
                        &policy.custom,
                    ],
                    |row| {
                        let pk = row.get("pk")?;
                        Ok(DbVal(
                            PostPolicy {
                                pk,
                                list: row.get("list")?,
                                announce_only: row.get("announce_only")?,
                                subscription_only: row.get("subscription_only")?,
                                approval_needed: row.get("approval_needed")?,
                                open: row.get("open")?,
                                custom: row.get("custom")?,
                            },
                            pk,
                        ))
                    },
                )
                .map_err(|err| {
                    if matches!(
                        err,
                        rusqlite::Error::SqliteFailure(
                            rusqlite::ffi::Error {
                                code: rusqlite::ffi::ErrorCode::ConstraintViolation,
                                extended_code: 787
                            },
                            _
                        )
                    ) {
                        Error::from(err)
                            .chain_err(|| NotFound("Could not find a list with this pk."))
                    } else {
                        err.into()
                    }
                })?;

            trace!("set_list_post_policy {:?}.", &ret);
            Ok(ret)
        }
    }
}

mod subscription_policy {
    use log::trace;
    use rusqlite::OptionalExtension;

    use crate::{
        errors::{ErrorKind::*, *},
        models::{DbVal, SubscriptionPolicy},
        Connection,
    };

    impl Connection {
        /// Fetch the subscription policy of a mailing list.
        pub fn list_subscription_policy(
            &self,
            pk: i64,
        ) -> Result<Option<DbVal<SubscriptionPolicy>>> {
            let mut stmt = self
                .connection
                .prepare("SELECT * FROM subscription_policy WHERE list = ?;")?;
            let ret = stmt
                .query_row([&pk], |row| {
                    let pk = row.get("pk")?;
                    Ok(DbVal(
                        SubscriptionPolicy {
                            pk,
                            list: row.get("list")?,
                            send_confirmation: row.get("send_confirmation")?,
                            open: row.get("open")?,
                            manual: row.get("manual")?,
                            request: row.get("request")?,
                            custom: row.get("custom")?,
                        },
                        pk,
                    ))
                })
                .optional()?;

            Ok(ret)
        }

        /// Remove an existing subscription policy.
        ///
        /// # Examples
        ///
        /// ```
        /// # use mailpot::{models::*, Configuration, Connection, SendMail};
        /// # use tempfile::TempDir;
        /// #
        /// # let tmp_dir = TempDir::new().unwrap();
        /// # let db_path = tmp_dir.path().join("mpot.db");
        /// # let config = Configuration {
        /// #     send_mail: SendMail::ShellCommand("/usr/bin/false".to_string()),
        /// #     db_path: db_path.clone(),
        /// #     data_path: tmp_dir.path().to_path_buf(),
        /// #     administrators: vec![],
        /// # };
        /// #
        /// # fn do_test(config: Configuration) {
        /// let db = Connection::open_or_create_db(config).unwrap().trusted();
        /// let list = db
        ///     .create_list(MailingList {
        ///         pk: 0,
        ///         name: "foobar chat".into(),
        ///         id: "foo-chat".into(),
        ///         address: "foo-chat@example.com".into(),
        ///         description: None,
        ///         topics: vec![],
        ///         archive_url: None,
        ///     })
        ///     .unwrap();
        /// # assert!(db.list_subscription_policy(list.pk()).unwrap().is_none());
        /// let pol = db
        ///     .set_list_subscription_policy(SubscriptionPolicy {
        ///         pk: -1,
        ///         list: list.pk(),
        ///         send_confirmation: false,
        ///         open: true,
        ///         manual: false,
        ///         request: false,
        ///         custom: false,
        ///     })
        ///     .unwrap();
        /// # assert_eq!(db.list_subscription_policy(list.pk()).unwrap().as_ref(), Some(&pol));
        /// db.remove_list_subscription_policy(list.pk(), pol.pk())
        ///     .unwrap();
        /// # assert!(db.list_subscription_policy(list.pk()).unwrap().is_none());
        /// # }
        /// # do_test(config);
        /// ```
        ///
        /// ```should_panic
        /// # use mailpot::{models::*, Configuration, Connection, SendMail};
        /// # use tempfile::TempDir;
        /// #
        /// # let tmp_dir = TempDir::new().unwrap();
        /// # let db_path = tmp_dir.path().join("mpot.db");
        /// # let config = Configuration {
        /// #     send_mail: SendMail::ShellCommand("/usr/bin/false".to_string()),
        /// #     db_path: db_path.clone(),
        /// #     data_path: tmp_dir.path().to_path_buf(),
        /// #     administrators: vec![],
        /// # };
        /// #
        /// # fn do_test(config: Configuration) {
        /// let db = Connection::open_or_create_db(config).unwrap().trusted();
        /// db.remove_list_post_policy(1, 1).unwrap();
        /// # }
        /// # do_test(config);
        /// ```
        pub fn remove_list_subscription_policy(&self, list_pk: i64, policy_pk: i64) -> Result<()> {
            let mut stmt = self.connection.prepare(
                "DELETE FROM subscription_policy WHERE pk = ? AND list = ? RETURNING *;",
            )?;
            stmt.query_row(rusqlite::params![&policy_pk, &list_pk,], |_| Ok(()))
                .map_err(|err| {
                    if matches!(err, rusqlite::Error::QueryReturnedNoRows) {
                        Error::from(err).chain_err(|| NotFound("list or list policy not found!"))
                    } else {
                        err.into()
                    }
                })?;

            trace!("remove_list_subscription_policy {} {}.", list_pk, policy_pk);
            Ok(())
        }

        /// Set the unique post policy for a list.
        pub fn set_list_subscription_policy(
            &self,
            policy: SubscriptionPolicy,
        ) -> Result<DbVal<SubscriptionPolicy>> {
            if !(policy.open || policy.manual || policy.request || policy.custom) {
                return Err(
                    "Cannot add empty policy. Having no policy is probably what you want to do."
                        .into(),
                );
            }
            let list_pk = policy.list;

            let mut stmt = self.connection.prepare(
                "INSERT OR REPLACE INTO subscription_policy(list, send_confirmation, open, \
                 manual, request, custom) VALUES (?, ?, ?, ?, ?, ?) RETURNING *;",
            )?;
            let ret = stmt
                .query_row(
                    rusqlite::params![
                        &list_pk,
                        &policy.send_confirmation,
                        &policy.open,
                        &policy.manual,
                        &policy.request,
                        &policy.custom,
                    ],
                    |row| {
                        let pk = row.get("pk")?;
                        Ok(DbVal(
                            SubscriptionPolicy {
                                pk,
                                list: row.get("list")?,
                                send_confirmation: row.get("send_confirmation")?,
                                open: row.get("open")?,
                                manual: row.get("manual")?,
                                request: row.get("request")?,
                                custom: row.get("custom")?,
                            },
                            pk,
                        ))
                    },
                )
                .map_err(|err| {
                    if matches!(
                        err,
                        rusqlite::Error::SqliteFailure(
                            rusqlite::ffi::Error {
                                code: rusqlite::ffi::ErrorCode::ConstraintViolation,
                                extended_code: 787
                            },
                            _
                        )
                    ) {
                        Error::from(err)
                            .chain_err(|| NotFound("Could not find a list with this pk."))
                    } else {
                        err.into()
                    }
                })?;

            trace!("set_list_subscription_policy {:?}.", &ret);
            Ok(ret)
        }
core/src/posts.rs (line 115)
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
    pub fn post(&self, env: &Envelope, raw: &[u8], _dry_run: bool) -> Result<()> {
        let result = self.inner_post(env, raw, _dry_run);
        if let Err(err) = result {
            return match self.insert_to_queue(QueueEntry::new(
                Queue::Error,
                None,
                Some(Cow::Borrowed(env)),
                raw,
                Some(err.to_string()),
            )?) {
                Ok(idx) => {
                    log::info!(
                        "Inserted mail from {:?} into error_queue at index {}",
                        env.from(),
                        idx
                    );
                    Err(err)
                }
                Err(err2) => {
                    log::error!(
                        "Could not insert mail from {:?} into error_queue: {err2}",
                        env.from(),
                    );

                    Err(err.chain_err(|| err2))
                }
            };
        }
        result
    }
core/src/subscriptions.rs (line 246)
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
    pub fn candidate_subscription(&self, pk: i64) -> Result<DbVal<ListCandidateSubscription>> {
        let mut stmt = self
            .connection
            .prepare("SELECT * FROM candidate_subscription WHERE pk = ?;")?;
        let val = stmt
            .query_row(rusqlite::params![&pk], |row| {
                let _pk: i64 = row.get("pk")?;
                debug_assert_eq!(pk, _pk);
                Ok(DbVal(
                    ListCandidateSubscription {
                        pk,
                        list: row.get("list")?,
                        address: row.get("address")?,
                        name: row.get("name")?,
                        accepted: row.get("accepted")?,
                    },
                    pk,
                ))
            })
            .map_err(|err| {
                if matches!(err, rusqlite::Error::QueryReturnedNoRows) {
                    Error::from(err)
                        .chain_err(|| NotFound("Candidate subscription with this pk not found!"))
                } else {
                    err.into()
                }
            })?;

        Ok(val)
    }

    /// Accept subscription candidate.
    pub fn accept_candidate_subscription(&self, pk: i64) -> Result<DbVal<ListSubscription>> {
        let val = self.connection.query_row(
            "INSERT INTO subscription(list, address, name, enabled, digest, verified, \
             hide_address, receive_duplicates, receive_own_posts, receive_confirmation) SELECT \
             list, address, name, 1, 0, 0, 0, 1, 1, 0 FROM candidate_subscription WHERE pk = ? \
             RETURNING *;",
            rusqlite::params![&pk],
            |row| {
                let pk = row.get("pk")?;
                Ok(DbVal(
                    ListSubscription {
                        pk,
                        list: row.get("list")?,
                        address: row.get("address")?,
                        account: row.get("account")?,
                        name: row.get("name")?,
                        digest: row.get("digest")?,
                        enabled: row.get("enabled")?,
                        verified: row.get("verified")?,
                        hide_address: row.get("hide_address")?,
                        receive_duplicates: row.get("receive_duplicates")?,
                        receive_own_posts: row.get("receive_own_posts")?,
                        receive_confirmation: row.get("receive_confirmation")?,
                    },
                    pk,
                ))
            },
        )?;

        trace!("accept_candidate_subscription {:?}.", &val);
        // table entry might be modified by triggers, so don't rely on RETURNING value.
        let ret = self.list_subscription(val.list, val.pk())?;

        // assert that [ref:accept_candidate] trigger works.
        debug_assert_eq!(Some(ret.pk), self.candidate_subscription(pk)?.accepted);
        Ok(ret)
    }

    /// Remove a subscription by their address.
    pub fn remove_subscription(&self, list_pk: i64, address: &str) -> Result<()> {
        self.connection
            .query_row(
                "DELETE FROM subscription WHERE list = ? AND address = ? RETURNING *;",
                rusqlite::params![&list_pk, &address],
                |_| Ok(()),
            )
            .map_err(|err| {
                if matches!(err, rusqlite::Error::QueryReturnedNoRows) {
                    Error::from(err).chain_err(|| NotFound("list or list owner not found!"))
                } else {
                    err.into()
                }
            })?;

        Ok(())
    }

    /// Update a mailing list subscription.
    pub fn update_subscription(&self, change_set: ListSubscriptionChangeset) -> Result<()> {
        let pk = self
            .list_subscription_by_address(change_set.list, &change_set.address)?
            .pk;
        if matches!(
            change_set,
            ListSubscriptionChangeset {
                list: _,
                address: _,
                account: None,
                name: None,
                digest: None,
                verified: None,
                hide_address: None,
                receive_duplicates: None,
                receive_own_posts: None,
                receive_confirmation: None,
                enabled: None,
            }
        ) {
            return Ok(());
        }

        let ListSubscriptionChangeset {
            list,
            address: _,
            name,
            account,
            digest,
            enabled,
            verified,
            hide_address,
            receive_duplicates,
            receive_own_posts,
            receive_confirmation,
        } = change_set;
        let tx = self.savepoint(Some(stringify!(update_subscription)))?;

        macro_rules! update {
            ($field:tt) => {{
                if let Some($field) = $field {
                    tx.connection.execute(
                        concat!(
                            "UPDATE subscription SET ",
                            stringify!($field),
                            " = ? WHERE list = ? AND pk = ?;"
                        ),
                        rusqlite::params![&$field, &list, &pk],
                    )?;
                }
            }};
        }
        update!(name);
        update!(account);
        update!(digest);
        update!(enabled);
        update!(verified);
        update!(hide_address);
        update!(receive_duplicates);
        update!(receive_own_posts);
        update!(receive_confirmation);

        tx.commit()?;
        Ok(())
    }

    /// Fetch account by pk.
    pub fn account(&self, pk: i64) -> Result<Option<DbVal<Account>>> {
        let mut stmt = self
            .connection
            .prepare("SELECT * FROM account WHERE pk = ?;")?;

        let ret = stmt
            .query_row(rusqlite::params![&pk], |row| {
                let _pk: i64 = row.get("pk")?;
                debug_assert_eq!(pk, _pk);
                Ok(DbVal(
                    Account {
                        pk,
                        name: row.get("name")?,
                        address: row.get("address")?,
                        public_key: row.get("public_key")?,
                        password: row.get("password")?,
                        enabled: row.get("enabled")?,
                    },
                    pk,
                ))
            })
            .optional()?;
        Ok(ret)
    }

    /// Fetch account by address.
    pub fn account_by_address(&self, address: &str) -> Result<Option<DbVal<Account>>> {
        let mut stmt = self
            .connection
            .prepare("SELECT * FROM account WHERE address = ?;")?;

        let ret = stmt
            .query_row(rusqlite::params![&address], |row| {
                let pk = row.get("pk")?;
                Ok(DbVal(
                    Account {
                        pk,
                        name: row.get("name")?,
                        address: row.get("address")?,
                        public_key: row.get("public_key")?,
                        password: row.get("password")?,
                        enabled: row.get("enabled")?,
                    },
                    pk,
                ))
            })
            .optional()?;
        Ok(ret)
    }

    /// Fetch all subscriptions of an account by primary key.
    pub fn account_subscriptions(&self, pk: i64) -> Result<Vec<DbVal<ListSubscription>>> {
        let mut stmt = self
            .connection
            .prepare("SELECT * FROM subscription WHERE account = ?;")?;
        let list_iter = stmt.query_map([&pk], |row| {
            let pk = row.get("pk")?;
            Ok(DbVal(
                ListSubscription {
                    pk: row.get("pk")?,
                    list: row.get("list")?,
                    address: row.get("address")?,
                    account: row.get("account")?,
                    name: row.get("name")?,
                    digest: row.get("digest")?,
                    enabled: row.get("enabled")?,
                    verified: row.get("verified")?,
                    hide_address: row.get("hide_address")?,
                    receive_duplicates: row.get("receive_duplicates")?,
                    receive_own_posts: row.get("receive_own_posts")?,
                    receive_confirmation: row.get("receive_confirmation")?,
                },
                pk,
            ))
        })?;

        let mut ret = vec![];
        for list in list_iter {
            let list = list?;
            ret.push(list);
        }
        Ok(ret)
    }

    /// Fetch all accounts.
    pub fn accounts(&self) -> Result<Vec<DbVal<Account>>> {
        let mut stmt = self
            .connection
            .prepare("SELECT * FROM account ORDER BY pk ASC;")?;
        let list_iter = stmt.query_map([], |row| {
            let pk = row.get("pk")?;
            Ok(DbVal(
                Account {
                    pk,
                    name: row.get("name")?,
                    address: row.get("address")?,
                    public_key: row.get("public_key")?,
                    password: row.get("password")?,
                    enabled: row.get("enabled")?,
                },
                pk,
            ))
        })?;

        let mut ret = vec![];
        for list in list_iter {
            let list = list?;
            ret.push(list);
        }
        Ok(ret)
    }

    /// Add account.
    pub fn add_account(&self, new_val: Account) -> Result<DbVal<Account>> {
        let mut stmt = self
            .connection
            .prepare(
                "INSERT INTO account(name, address, public_key, password, enabled) VALUES(?, ?, \
                 ?, ?, ?) RETURNING *;",
            )
            .unwrap();
        let ret = stmt.query_row(
            rusqlite::params![
                &new_val.name,
                &new_val.address,
                &new_val.public_key,
                &new_val.password,
                &new_val.enabled,
            ],
            |row| {
                let pk = row.get("pk")?;
                Ok(DbVal(
                    Account {
                        pk,
                        name: row.get("name")?,
                        address: row.get("address")?,
                        public_key: row.get("public_key")?,
                        password: row.get("password")?,
                        enabled: row.get("enabled")?,
                    },
                    pk,
                ))
            },
        )?;

        trace!("add_account {:?}.", &ret);
        Ok(ret)
    }

    /// Remove an account by their address.
    pub fn remove_account(&self, address: &str) -> Result<()> {
        self.connection
            .query_row(
                "DELETE FROM account WHERE address = ? RETURNING *;",
                rusqlite::params![&address],
                |_| Ok(()),
            )
            .map_err(|err| {
                if matches!(err, rusqlite::Error::QueryReturnedNoRows) {
                    Error::from(err).chain_err(|| NotFound("account not found!"))
                } else {
                    err.into()
                }
            })?;

        Ok(())
    }
core/src/templates.rs (line 334)
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
    pub fn add_template(&self, template: Template) -> Result<DbVal<Template>> {
        let mut stmt = self.connection.prepare(
            "INSERT INTO template(name, list, subject, headers_json, body) VALUES(?, ?, ?, ?, ?) \
             RETURNING *;",
        )?;
        let ret = stmt
            .query_row(
                rusqlite::params![
                    &template.name,
                    &template.list,
                    &template.subject,
                    &template.headers_json,
                    &template.body
                ],
                |row| {
                    let pk = row.get("pk")?;
                    Ok(DbVal(
                        Template {
                            pk,
                            name: row.get("name")?,
                            list: row.get("list")?,
                            subject: row.get("subject")?,
                            headers_json: row.get("headers_json")?,
                            body: row.get("body")?,
                        },
                        pk,
                    ))
                },
            )
            .map_err(|err| {
                if matches!(
                    err,
                    rusqlite::Error::SqliteFailure(
                        rusqlite::ffi::Error {
                            code: rusqlite::ffi::ErrorCode::ConstraintViolation,
                            extended_code: 787
                        },
                        _
                    )
                ) {
                    Error::from(err).chain_err(|| NotFound("Could not find a list with this pk."))
                } else {
                    err.into()
                }
            })?;

        trace!("add_template {:?}.", &ret);
        Ok(ret)
    }
source

pub fn description(&self) -> &str

A short description of the error. This method is identical to Error::description()

source§

impl Error

source

pub fn new_external<S: Into<String>>(msg: S) -> Self

Helper function to create a new generic error message.

Examples found in repository?
core/src/queue.rs (line 65)
57
58
59
60
61
62
63
64
65
66
67
    fn from_str(s: &str) -> Result<Self> {
        Ok(match s.trim() {
            s if s.eq_ignore_ascii_case(stringify!(Maildrop)) => Self::Maildrop,
            s if s.eq_ignore_ascii_case(stringify!(Hold)) => Self::Hold,
            s if s.eq_ignore_ascii_case(stringify!(Deferred)) => Self::Deferred,
            s if s.eq_ignore_ascii_case(stringify!(Corrupt)) => Self::Corrupt,
            s if s.eq_ignore_ascii_case(stringify!(Out)) => Self::Out,
            s if s.eq_ignore_ascii_case(stringify!(Error)) => Self::Error,
            other => return Err(Error::new_external(format!("Invalid Queue name: {other}."))),
        })
    }

Trait Implementations§

source§

impl ChainedError for Error

§

type ErrorKind = ErrorKind

Associated kind type.
source§

fn from_kind(kind: Self::ErrorKind) -> Self

Constructs an error from a kind, and generates a backtrace.
source§

fn with_chain<E, K>(error: E, kind: K) -> Selfwhere E: Error + Send + 'static, K: Into<Self::ErrorKind>,

Constructs a chained error from another error and a kind, and generates a backtrace.
source§

fn kind(&self) -> &Self::ErrorKind

Returns the kind of the error.
source§

fn iter(&self) -> Iter<'_>

Iterates over the error chain.
source§

fn chain_err<F, EK>(self, error: F) -> Selfwhere F: FnOnce() -> EK, EK: Into<ErrorKind>,

Extends the error chain with a new entry.
source§

fn backtrace(&self) -> Option<&Backtrace>

Returns the backtrace associated with this error.
source§

fn display_chain<'a>(&'a self) -> DisplayChain<'a, Self>

Returns an object which implements Display for printing the full context of this error. 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, f: &mut Formatter<'_>) -> Result

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

impl Error for Error

source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
source§

fn source(&self) -> Option<&(dyn Error + 'static)>

The lower-level source of this error, if any. Read more
1.0.0 · source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
source§

fn provide<'a>(&'a self, demand: &mut Demand<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type based access to context intended for error reports. Read more
source§

impl<'a> From<&'a str> for Error

source§

fn from(s: &'a str) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

Error returned from e-mail protocol operations from melib crate.

source§

fn from(e: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

Error returned from internal I/O operations.

source§

fn from(e: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

Error returned from sqlite3.

source§

fn from(e: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

Error from deserializing JSON values.

source§

fn from(e: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

Error returned from an external user initiated operation such as deserialization or I/O.

source§

fn from(e: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

Error returned from minijinja template engine.

source§

fn from(e: Error) -> Self

Converts to this type from the input type.
source§

impl From<Error> for ErrorKind

source§

fn from(e: Error) -> Self

Converts to this type from the input type.
source§

impl From<ErrorKind> for Error

source§

fn from(e: ErrorKind) -> Self

Converts to this type from the input type.
source§

impl From<String> for Error

source§

fn from(s: String) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Error

§

impl Send for Error

§

impl !Sync for Error

§

impl Unpin for Error

§

impl !UnwindSafe for Error

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. 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 Twhere 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<E> Provider for Ewhere E: Error + ?Sized,

source§

fn provide<'a>(&'a self, demand: &mut Demand<'a>)

🔬This is a nightly-only experimental API. (provide_any)
Data providers should implement this method to provide all values they are able to provide by using demand. Read more
source§

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

source§

default fn to_string(&self) -> String

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

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

§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

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

§

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.