asdb_taxa/
errors.rs

1// Copyright 2023 Danmarks Tekniske Universitet
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! ASDB taxa error definitions
16
17use std::error;
18use std::fmt;
19use std::io;
20use std::num;
21
22use regex;
23use serde_json;
24
25#[derive(Debug)]
26pub enum ASDBTaxonError {
27    Io(io::Error),
28    InvalidTaxId(String),
29    NotFound(i64),
30    JSONParserError(serde_json::Error),
31    IntParserError(num::ParseIntError),
32    RegexError(regex::Error),
33}
34
35macro_rules! implement_custom_error_from {
36    ($f: ty, $e: expr) => {
37        impl From<$f> for ASDBTaxonError {
38            fn from(f: $f) -> ASDBTaxonError {
39                $e(f)
40            }
41        }
42    };
43}
44
45implement_custom_error_from!(io::Error, ASDBTaxonError::Io);
46implement_custom_error_from!(serde_json::Error, ASDBTaxonError::JSONParserError);
47implement_custom_error_from!(num::ParseIntError, ASDBTaxonError::IntParserError);
48implement_custom_error_from!(regex::Error, ASDBTaxonError::RegexError);
49
50impl fmt::Display for ASDBTaxonError {
51    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52        match *self {
53            ASDBTaxonError::Io(ref err) => write!(f, "IO error: {}", err),
54            ASDBTaxonError::InvalidTaxId(ref err) => write!(f, "Invalid TaxID: {}", err),
55            ASDBTaxonError::NotFound(ref err) => write!(f, "TaxID not found: {}", err),
56            ASDBTaxonError::JSONParserError(ref err) => write!(f, "Failed to parse JSON: {}", err),
57            ASDBTaxonError::IntParserError(ref err) => write!(f, "Failed to parse int: {}", err),
58            ASDBTaxonError::RegexError(ref err) => write!(f, "Failed to generate regex: {}", err),
59        }
60    }
61}
62
63impl error::Error for ASDBTaxonError {
64    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
65        match *self {
66            ASDBTaxonError::Io(ref err) => Some(err),
67            ASDBTaxonError::JSONParserError(ref err) => Some(err),
68            ASDBTaxonError::IntParserError(ref err) => Some(err),
69            ASDBTaxonError::RegexError(ref err) => Some(err),
70            ASDBTaxonError::NotFound(_) | ASDBTaxonError::InvalidTaxId(_) => None,
71        }
72    }
73}