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. | ||
= | = Errors = | ||
<blockquote> | <blockquote> | ||
== Error Objects == | |||
<blockquote> | |||
Go prefers passing error objects as return values to exceptions.<br> | |||
Errors can be any object that expose the <code>Error</code> method. | |||
<syntaxhighlight lang="go"> | <syntaxhighlight lang="go"> | ||
require "errors" | |||
require "fmt" | |||
// error interface | |||
type error interface { | |||
Error() string | |||
} | } | ||
// build ad-hoc error | |||
fmt.Errorf("User does not exist") | |||
errors.New("User does not exist") | |||
</syntaxhighlight> | |||
Functions generally return an error as the last value | |||
<syntaxhighlight lang="go"> | |||
func doThing (value int, error) { | |||
return nil, fmt.Errorf("User does not exist") | |||
} | |||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- | </blockquote><!-- Error Objects --> | ||
== Error Verification == | |||
<blockquote> | |||
</blockquote><!-- Error Verification --> | |||
</blockquote><!-- Errors --> | |||
= Panic = | = Panic = |
Revision as of 12:57, 18 June 2022
Go seems to discourage the use of exception-style control-flows,
encouraging the use of errors in return-values instead.
Errors
Error Objects
Go prefers passing error objects as return values to exceptions.
Errors can be any object that expose theError
method.require "errors" require "fmt" // error interface type error interface { Error() string } // build ad-hoc error fmt.Errorf("User does not exist") errors.New("User does not exist")Functions generally return an error as the last value
func doThing (value int, error) { return nil, fmt.Errorf("User does not exist") }Error Verification
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 }