Error Handling in Go: This Is The Way
Description
The image is a meme based on a still of the title character from the Star Wars series 'The Mandalorian'. The top of the image has white text that reads, 'When someone asks about error handling in Go'. The bottom of the image shows the Mandalorian with a subtitle that has been edited to say, 'errors are part of my religion.' The word 'errors' is distinctly placed in a black box to show it's an alteration of the original quote, 'Weapons are part of my religion.' The meme humorously critiques or, depending on perspective, celebrates the error handling philosophy of the Go programming language. Go eschews traditional try-catch exception handling in favor of explicitly returning error values from functions. This leads to a ubiquitous 'if err != nil' pattern that developers must handle constantly, making error checking a core, almost ritualistic, part of writing Go code, hence the 'religion' analogy
Comments
22Comment deleted
Go's approach to error handling is simple: if err != nil, return err. Repeat this enough times and you achieve enlightenment, or at least a call stack so deep you can see the kernel
Every ‘if err != nil { return fmt.Errorf("%w: %v", err, ctx) }’ is just another bead on the Go rosary - we’re not handling errors, we’re saying Our Fathers so future SREs don’t page us at 3 a.m
After 15 years of advocating for proper error handling across multiple languages, I've come to appreciate Go's approach - it's like pair programming with a paranoid QA engineer who questions every single line of code. Sure, your codebase is 40% error checks, but at least you know exactly where that nil pointer came from at 3 AM in production
Go developers checking 'if err != nil' after every function call isn't defensive programming - it's a religious practice. While other languages hide their sins behind try-catch blocks and let exceptions bubble up like technical debt, Gophers face their errors head-on with the stoic determination of a Mandalorian. Sure, your codebase might look like a vertical accordion of error checks, but at least you'll never wonder where that panic came from at 3 AM. This is the way... to production stability, even if it means your error handling code is longer than your business logic
In Go, errors aren't exceptions - they're values you salute before propagating, lest panic enforces the creed
In Go, exceptions are heresy; the faithful return (value, err), chant “if err != nil,” and argue %w vs sentinel like a doctrine committee
In Go, “this is the way” compiles to: if err != nil { return fmt.Errorf("%w", err) } - repeated for every call in the stack
Сложна, реквестую Помощь зала! Comment deleted
В го функции могут возвращать несколько значений, соответственно ошибки принято передавать как одно из значений, а потом проверять ифом Comment deleted
Спасибо, друг) Comment deleted
Ээ э э ты зачем аватарку спиздил Comment deleted
Это сильно отличается от хендлинга ошибок в других языках, но мне нравится Comment deleted
Смотря каких. В Rust похожий принцип с Result вариантом, который они позаимствовали у Ocaml-а, который в свою очередь позаимствовал это у Haskell с его Either Monad. А тот скорее всего еще у кого-то) Comment deleted
В Го нету исключений, поэтому ошибка это одно из возвращаемых значений функции Comment deleted
Типа как опционалы (nullable) в других языках? Comment deleted
Примерно так: f, err := os.Open("path to file") if err != nil { panic(err) } Comment deleted
В C++ кстати тоже такое хотят завезти через std::expected Comment deleted
https://www.youtube.com/watch?v=kaI4R0Ng4E8 кто хотел у Александреску уже сам срисовал)) Comment deleted
No Comment deleted
Мой краб Comment deleted
Верни краба Comment deleted
Не верну, у меня он уже давно живёт :₽ Comment deleted