Golang errors: Difference between revisions
From wikinotes
No edit summary |
|||
Line 2: | Line 2: | ||
encouraging the use of errors in return-values instead. | encouraging the use of errors in return-values instead. | ||
= | = Returned Errors = | ||
<blockquote> | <blockquote> | ||
Except for very exceptional circumstances, go encourages the use of returned error values. | |||
<syntaxhighlight lang="go"> | <syntaxhighlight lang="go"> | ||
func sudo(user string, command string) (exitcode int, error) { | |||
// ... | |||
if success { | |||
return 0, nil | |||
} | |||
return 1, fmt.Errorf("User does not exist") | |||
} | |||
output, err := sudo("root", "cat /etc/passwd"); | |||
</syntaxhighlight> | |||
</blockquote><!-- Returned Errors --> | |||
= Panic = | |||
<blockquote> | |||
== panic == | |||
<blockquote> | |||
A <code>panic</code> is go's repacement for exceptions.<br> | |||
If a panic is not caught, it bubbles to the top of the application, and it exits with an error. | |||
<syntaxhighlight lang="go"> | |||
panic("I encountered an error") | |||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- panic --> | |||
== recover == | |||
<blockquote> | |||
You can check the value of a panic (if one has been raised) using <code>recover()</code>. | |||
<syntaxhighlight lang="go"> | |||
panic("I encountered an error") // raise a panic | |||
err := recover() // returns nil/error-msg-if-present | |||
</syntaxhighlight> | |||
It is common to handle panics in deferred functions | It is common to handle panics in deferred functions | ||
Line 29: | Line 58: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- panic and recover --> | </blockquote><!-- panic and recover --> | ||
</blockquote><!-- Panic --> |
Revision as of 15:55, 6 June 2022
Go seems to discourage the use of exception-style control-flows,
encouraging the use of errors in return-values instead.
Returned Errors
Except for very exceptional circumstances, go encourages the use of returned error values.
func sudo(user string, command string) (exitcode int, error) { // ... if success { return 0, nil } return 1, fmt.Errorf("User does not exist") } output, err := sudo("root", "cat /etc/passwd");
Panic
panic
A
panic
is go's repacement for exceptions.
If a panic is not caught, it bubbles to the top of the application, and it exits with an error.panic("I encountered an error")recover
You can check the value of a panic (if one has been raised) using
recover()
.panic("I encountered an error") // raise a panic err := recover() // returns nil/error-msg-if-presentIt is common to handle panics in deferred functions
func main() { fmt.Println("hi") panic("I just encountered an error") defer func() { if err := recover(); err != nil { fmt.Println("Error: ", err) panic(err) // <<-- re-raise panic } } fmt.Println("bye") // <-- never runs }