I've always been a huge fan of both Rust and GoLang. Their approaches to programming, particularly in error handling, have resonated with me throughout my career. After dedicating over four years to GoLang development, I recently transitioned to a project where I'm refactoring legacy PHP code into a newer, more robust version. This shift has been both exciting and challenging, especially when it comes to adapting to PHP's traditional error-handling mechanisms.
Having grown accustomed to Go's "errors as values" concept, switching back to languages that rely on the conventional try-catch paradigm has been a significant adjustment. The idea of expecting the unexpected through exceptions feels counterintuitive. In GoLang, errors are treated as explicit return values that functions can produce, requiring developers to handle them directly. This explicitness promotes clarity and encourages thorough error checking at every function call.
In contrast, exception-based error handling can sometimes lead to overlooked edge cases. It's possible to call a function that throws an exception and only discover the oversight in production when the application crashes a scenario every developer aims to avoid.
To address this challenge, I decided to introduce a Rust-inspired Result
type in my PHP controller methods. Rust's approach to error handling, much like Go's, emphasizes returning results that explicitly indicate success or failure. By implementing a Result
type in PHP, I aimed to bring this level of explicitness and safety to my current project.
For instance, in the user registration endpoint, I wrapped Laravel’s validator to return a Result
containing either a valid value or an error. This modification allows me to explicitly handle validation failures, enabling the application to return a 422 Unprocessable Entity status code when appropriate. Not only does this make the error handling more transparent, but it also improves the API's reliability by ensuring that all potential errors are accounted for and managed properly.
Here are some key benefits I've observed from this approach:
- Enhanced Readability: By handling errors explicitly, the code becomes more readable and maintainable. Developers can see at a glance where errors might occur and how they're managed.
- Improved Reliability: Explicit error handling reduces the risk of uncaught exceptions causing unexpected crashes in production environments.
- Consistency Across Languages: Adopting a Result type in PHP brings the language's error-handling closer to that of Rust and GoLang, which can be beneficial for teams working across multiple languages.
To provide a clearer picture of this methodology, I've prepared three code examples to highlight the contrasts and similarities between the languages and showcase how adopting certain patterns can lead to more robust and maintainable code.
Golang
Rust
I'm curious to hear your thoughts on this approach. Do you think incorporating concepts from one language into another is beneficial in the long run?
Feel free to share your experiences or ask any questions.
Top comments (8)
I think your implementation doesn't really replicate both approachs, and is a bit too raw, you have a middle ground between Rust and Go approachs, but with the bad sides of both.
Actually you can do the same as Go in PHP, because PHP has the destructuring feature (the list), and all that Go does is return a tuple:
I can make a similar argument for the Rust example (because PHP enums can be used on match expressions), but the PHP version is a bit verbose to declare, and actually pretty elegant on usage:
This is just glorified status codes that were the problem all those years ago when we invented exceptions to solve the madness that was error handling on procedural languages via defensive programming, as you didn't have a way to force the programmers to handle all the possible errors, the actual error handling was tied to knowing the documentation of the possible returns of that function (much like most of the PHP functions where you need to read the docs to understand the meaning of the return values).
Exceptions will blow out the code on the spot, so this forces you to at least know that the error exist. The biggest win we gain when using Exceptions is programming only worrying about the happy path, and leaving to handle the error path on a later moment of the code.
Functional languages, and Rust by extension, have a way to use a status code-like solution and still have similar benefits to Exceptions because their compilers enforces exhaustive type check on the match blocks so you still are required to handle all the possible errors by a type-level constraint, so you retain the requirement of knowing all the possible outcomes in the code and handle them all.
If was just that, the argument would end much like the Go approach of being just a better status code, but not much an improvement over Exceptions, so people won't become crazy hyped about function error handling and shitting over exception like they are now.
The big advantage of the functional approuch is not handle the error with defensive programming that forces you to think about both happy and error paths at the same time, but in a monadic-way, so that we can apply the idea of the railway oriented programming, and just handle the happy path first, and after handle the error path, while having the ability of compose the errors (which you have to do manually in the Go approuch).
So that instead of handling the values and worrying about them being null, you can just compose the computations that should be applied on them, by using the map and mapError operations, so you never touch the internal value of the Resut directly.
PHP has some degree of support for FP, but clearly it more idiomatic code would be more OO or procedural style, so or you stick to Go style handling, or we could adapt the Rust style to implement a Result monad-like type in a OO style rather than in a FP style, by relying on, surprisingly, inheritance, and implement a object similar to how booleans should be implemented in a OO-way:
This solution, in my opinion, translates better the objectives we trying to get from Exceptions, Rust and Go error handling styles. Because we can actually:
This is astonishing! Thank you so much for clarifying and elaborating more on the topic. I really appreciate what you did. The example I provided was more of a baseline to show the basic approach I took.
My later implementation is based around an abstract class to define the base functions. I was also considering wrapping exceptions inside the Err wrapper so that the try-catch statement would only need to handle the Result.
I introduced flatMap to chain operations seamlessly. It ensures that if any operation fails, the entire chain short-circuits to the error path without executing the subsequent steps. This aligns with the principles of railway-oriented programming, allowing us to focus on the happy path first and handle errors separately. By encapsulating exceptions within the Err wrapper, we can manage errors more gracefully and maintain a consistent approach throughout the codebase.
besides liking more to have a match method to mantain the hability to compose functions to handle both cases, i really liked your approuch to the unwrap method, it makes it much more safe than just unwrap the value returning a union type, if i implement a type like this in the future, i would incorporate this in the API too.
Sounds like you want to use Gernics, and you can alread use them in php, validated via phpstan (in the CI pipeline) and with autocompletion via e.g. Phpstorm: chatgpt.com/share/671d8224-edb8-80...
Thanks for the reply. I do use PHPStorm, and it warns me about possible PHPStan issues with the functions. I'm familiar with PHPStan, but that's not the case here. I just want to implement a more comprehensive and easy-to-understand error handling model in PHP.
Thanks for the post, I was literally thinking about this Idea after touching golang and was interested in your exploration of this idea. Pros of this approach - explicit handling of all possible errors, this makes programmers think of it at least for a bit and something about it. Though good programmers should do it anyway. The cons - code bloat. Imagine there might be 5 or even more possible errors, and a chain of method calls - this would produce pretty long switch/match expressions in multiple places. This is not bad per se, just a tradeoff. With exceptions you could hide under the carpet all cases that you do not foresee or don't bother to care and simply handle all other cases with general catch{Throwable}. Another point is that there could be an exception thrown in your switch/match if you would try to do something more sophisticated than checking length and call some custom logic. I think php relies on exceptions heavily and passed point of no return, to me using this approach in php is something similar to using raise / recover in go. Not impossible but somewhat strange. Thanks again for the post!
Thanks for the thoughtful comment! I totally agree that exceptions still have their place, and in some cases, they’re inevitable. My focus here is more on minimizing the need for exceptions by handling errors explicitly wherever possible. For cases where exceptions might still be thrown, I’m considering wrapping those exceptions — catching them and returning an error instead. This way, we keep the flow simple and predictable, which is a key part of my approach.
Regarding the potential for switch/match bloat, I’m aiming to follow Go’s philosophy to achieve simplicity. In Go, any error halts the flow, and I’m applying that same principle in PHP. Rather than matching every possible error, I’m sticking to essential cases only, stopping the program flow if
Result->error !== null
. This keeps the code manageable and avoids unnecessary branching, allowing the program to respond only when errors arise without clutter.Thanks again for sharing your insights!
I would like to know what version of PHP are you running.
If you are using PHP 8, you can use
match
for this one. This way it's much closer toRust
.