promptpay_rs/error.rs
1use std::{error::Error, fmt};
2
3/// Custom error type for PromptPay QR generation failures.
4///
5/// This error is used throughout the library to indicate issues such as:
6/// - Empty merchant ID
7/// - Invalid payload
8/// - QR code generation failure
9#[derive(Debug)]
10pub struct PromptPayError {
11 details: String, // ข้อความอธิบายข้อผิดพลาด
12}
13
14impl PromptPayError {
15 /// Creates a new `PromptPayError` with a custom message.
16 ///
17 /// # Arguments
18 /// * `msg` - A descriptive error message
19 ///
20 /// # Returns
21 /// A new `PromptPayError` instance
22 ///
23 /// # Example
24 /// ```rust
25 /// use promptpay_rs::PromptPayError;
26 /// let err = PromptPayError::new("Invalid phone number");
27 /// ```
28 pub fn new(msg: &str) -> PromptPayError {
29 PromptPayError {
30 details: msg.to_string(),
31 }
32 }
33}
34
35impl fmt::Display for PromptPayError {
36 /// Formats the error for display (e.g., in `println!` or `eprintln!`).
37 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
38 write!(f, "{}", self.details)
39 }
40}
41
42impl Error for PromptPayError {
43 /// Returns a short description of the error (legacy method).
44 ///
45 /// **Note**: Prefer using `Display` implementation for user-facing messages.
46 fn description(&self) -> &str {
47 &self.details
48 }
49}