DEV Community

Discussion on: Introduction to Go for PHP Developers

Collapse
 
dopitz profile image
Daniel O. • Edited

In Go, errors are not treated like exceptions. There is no throw or catch mechanism. Instead, errors are returned from functions if one has occurred.

This is a "no go" for me.

Collapse
 
restoreddev profile image
Andrew Davis

It’s not as bad as you might think. It forces you to account for each error which makes your code a little more resilient.

Collapse
 
igormp profile image
Igor Moura

I honestly love it. As a hardcore C user, it feels pretty natural to me and makes you deal with the error as soon as possible instead of ignoring it.

Collapse
 
presto412 profile image
Priyansh Jain

Can second this

Collapse
 
okolbay profile image
andrew • Edited

4 steps to love it:
1 try to implement clean project structure
2 use exceptions to propagate errors
3 realize that exception is part of interface, and to avoid coupling, or catching SQL exceptions in HTTP controller you need exception per layer
4 give up and embrace go’s way of handling errors

not to mention that throw is essentialy a GOTO instruction, its slow and ask yourself - how many times, when catching “business-logic” related exception from your code you were interested in stacktrace?

Collapse
 
david_j_eddy profile image
David J Eddy

I read that same line and instantly thought `oh, crap. error catching is going to be a mess'. But then I thought about it; most error catching I do should be handled in a much more graceful way. Not a 'here is an error, return stack trace'. After reading this article I feel like going Go a try, again.

Collapse
 
ameliagapin profile image
Amelia Gapin

At first, I wasn't a fan of this. It made the code feel cumbersome. After a bit, I not only got used to it, but came to embrace it. It makes error handling much more a natural part of the way you code. You can avoid the scoping of a try/catch block because you don't have to put your code into another block.

The compiler will ensure that you've recognized the error is part of the return (when using a multi-return function) so you don't have to worry about being unaware of it. If you do anything with it and what you do is up to you. You could choose to ignore it by assigning it to _ instead of a variable.