Skip to main content

coap_message_implementations/
error.rs

1use crate::option_extension::ExtensionError;
2use coap_message::error::RenderableOnMinimal;
3
4/// Error type for manipulation of [`crate::inmemory_write`] messages.
5///
6/// This is presented externally as an internal server error, but has enough structure to be useful
7/// for debugging through `dbg!()`.
8#[derive(Debug, thiserror::Error)]
9#[cfg_attr(feature = "defmt", derive(defmt::Format))]
10#[non_exhaustive]
11pub enum WriteError {
12    #[error("operations did not adhere to required sequence")]
13    OutOfSequence,
14    #[error("no space in buffer")]
15    OutOfSpace,
16    #[error("options inside the message were encoded badly")]
17    BadEncoding,
18}
19
20impl RenderableOnMinimal for WriteError {
21    type Error<IE: RenderableOnMinimal + core::fmt::Debug> = IE;
22    fn render<M: coap_message::MinimalWritableMessage>(
23        self,
24        msg: &mut M,
25    ) -> Result<(), Self::Error<M::UnionError>> {
26        coap_message_utils::Error::internal_server_error().render::<M>(msg)
27    }
28}
29
30impl From<core::convert::Infallible> for WriteError {
31    fn from(never: core::convert::Infallible) -> Self {
32        match never {}
33    }
34}
35
36impl From<ExtensionError> for WriteError {
37    fn from(_value: ExtensionError) -> Self {
38        Self::BadEncoding
39    }
40}
41
42#[test]
43fn test_error_format() {
44    extern crate std;
45    use std::{format, string::String};
46
47    fn render(e: &dyn core::error::Error) -> String {
48        format!("{}", e)
49    }
50    // Not necessarily *exactly* like that text, but something like it, and implementing Error
51    assert_eq!(render(&WriteError::OutOfSpace), "no space in buffer");
52}