coap_server/app/
error.rs

1use std::fmt::Debug;
2use std::{error, fmt};
3
4use coap_lite::error::HandlingError;
5use coap_lite::ResponseType;
6
7/// Error type which can be converted to a [`crate::app::Response`] as a convenience for allowing
8/// Rust's `?` operator to work naturally in handler code without violating the protocol by
9/// failing to respond to requests.
10#[derive(Debug, Clone)]
11pub struct CoapError {
12    pub code: Option<ResponseType>,
13    pub message: String,
14}
15
16impl CoapError {
17    pub fn internal(msg: impl ToString) -> Self {
18        Self::for_code(ResponseType::InternalServerError, msg)
19    }
20
21    pub fn bad_request(msg: impl ToString) -> Self {
22        Self::for_code(ResponseType::BadRequest, msg)
23    }
24
25    pub fn not_found() -> Self {
26        Self::for_code(ResponseType::NotFound, "Not found")
27    }
28
29    pub fn method_not_allowed() -> Self {
30        Self::for_code(ResponseType::MethodNotAllowed, "Method not allowed")
31    }
32
33    pub fn for_code(code: ResponseType, msg: impl ToString) -> Self {
34        Self {
35            code: Some(code),
36            message: msg.to_string(),
37        }
38    }
39
40    pub(crate) fn into_handling_error(self) -> HandlingError {
41        HandlingError {
42            code: self.code,
43            message: self.message,
44        }
45    }
46}
47
48impl fmt::Display for CoapError {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        write!(f, "Handling error {:?}: {}", self.code, self.message)
51    }
52}
53
54impl error::Error for CoapError {}
55
56impl From<HandlingError> for CoapError {
57    fn from(src: HandlingError) -> Self {
58        Self {
59            message: src.message,
60            code: src.code,
61        }
62    }
63}