void/notes/error-handling.md
2024-10-20 22:20:02 -03:00

40 lines
1.3 KiB
Markdown

---
title: "Error Handling"
tags:
- #coding
- #design-patterns
- #errors
created: 2024-10-20 16:45
---
# Error Handling
Different ways to handle errors in code
## Errors as Exceptions - Try Catch
### Try Catch
## Errors as Values
### `Result<T, Err>` - `Option<T>`
The `Result<T, Err>` type (sometimes also called `Option<T>`, `Maybe<T>`, or others)
is a custom data type that may or may not have a value, but like the
Schrödinger's box, we won't know until we peak inside of it, forcing the code
to handle both cases.
This data type can be use to solve 2 common pitfals:
- `Result<T, Err>`: this data can have a value (sometimes called `Ok(T)`), or can hold an error.
- `Option<T>`: this data can have a value (sometimes called `Some(T)`) or can not have a value (sometimes called `None()`).
This data type is often used with [[pattern matching]], allowing to handle each possible variation of the type.
Resources:
- [[Readwise/Monad Is Actually Easy.|This data type is a monad]]
- Rust [`Option<T>`](https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html#the-option-enum-and-its-advantages-over-null-values) and [`Result<T, E>`](https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html) types.
- Gleam [`Option(a)`](https://hexdocs.pm/gleam_stdlib/gleam/option.html) type.
### Return touples