> For the complete documentation index, see [llms.txt](https://weerasak-chongnguluam.gitbook.io/sedoc/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://weerasak-chongnguluam.gitbook.io/sedoc/rust/error.md).

# Error

### Implements Error trait

จาก

{% embed url="<https://doc.rust-lang.org/std/error/trait.Error.html>" %}

เราต้อง implements Debug กับ Display ก่อน ซึ่ง Debug เราใช้ derive ได้ แต่ Display ต้อง implement เอง

ส่วน method ของ Error trait จริงๆ ไม่ต้อง implements ก็ได้มันมี default

```rust
#[derive(Debug)]
struct SuperErrorSideKick;

impl fmt::Display for SuperErrorSideKick {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "SuperErrorSideKick is here!")
    }
}

impl Error for SuperErrorSideKick {}
```

แต่ที่จะได้ implements เองบ่อยๆก็คือ method source เผื่อในกรณีที่เราต้องการให้เข้าถึง Error ที่เรา wrap เอาไว้ได้เช่นมี SuperError ที่มี SuperErrorSideKick เป็น field ข้างในแบบนี้

```rust
#[derive(Debug)]
struct SuperError {
    side: SuperErrorSideKick,
}

impl fmt::Display for SuperError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "SuperError is here!")
    }
}

impl Error for SuperError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&self.side)
    }
}
```
