xref: /aosp_15_r20/system/authgraph/core/src/error.rs (revision 4185b0660fbe514985fdcf75410317caad8afad1)
1 // Copyright 2023 Google LLC
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 ////////////////////////////////////////////////////////////////////////////////
16 
17 //! Error Handling
18 
19 use alloc::string::String;
20 use authgraph_wire::ErrorCode;
21 use coset::CoseError;
22 
23 /// AuthGraph error type.
24 #[derive(Debug)]
25 pub struct Error(pub ErrorCode, pub String);
26 
27 impl core::convert::From<CoseError> for Error {
from(e: CoseError) -> Self28     fn from(e: CoseError) -> Self {
29         crate::ag_err!(InternalError, "CoseError: {}", e)
30     }
31 }
32 
33 impl From<alloc::collections::TryReserveError> for Error {
from(e: alloc::collections::TryReserveError) -> Self34     fn from(e: alloc::collections::TryReserveError) -> Self {
35         crate::ag_err!(MemoryAllocationFailed, "allocation of Vec failed: {:?}", e)
36     }
37 }
38 
39 /// Macro to build an [`Error`] instance.
40 /// E.g. use: `ag_err!(InternalError, "some {} format", arg)`.
41 #[macro_export]
42 macro_rules! ag_err {
43     { $error_code:ident, $($arg:tt)+ } => {
44         Error(ErrorCode::$error_code,
45               alloc::format!("{}:{}: {}", file!(), line!(), format_args!($($arg)+))) };
46 }
47 
48 /// Macro to build an [`Error`] instance.
49 /// E.g. use: `ag_verr!(rc, "some {} format", arg)`.
50 #[macro_export]
51 macro_rules! ag_verr {
52     { $error_code:expr, $($arg:tt)+ } => {
53           Error($error_code,
54                 alloc::format!("{}:{}: {}", file!(), line!(), format_args!($($arg)+))) };
55 }
56