Last active
June 12, 2016 07:45
-
-
Save nicerobot/263869942dd5344d9cd6943af5b5ddf2 to your computer and use it in GitHub Desktop.
The versatility of Go errors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Note: This is _just_ an example of the versatility of Go, or, more specifically, first-class functions and duck-typing. | |
package main | |
import "log" | |
type R string | |
type E func() string | |
// An example of a "catch" error function factory. | |
var Failure = func(message string, callback func()) error { | |
return E(func() string { | |
log.Printf("%s failed. I can handle it here.", message) | |
callback() | |
return message | |
}) | |
} | |
// This makes E an error. | |
func (e E) Error() string { | |
return e() | |
} | |
// A more simplistic way to handle errors. | |
func catch(r R, err error) R { | |
if err != nil { | |
log.Println(err) | |
} | |
return r | |
} | |
// A similar simplistic way to make an error exceptional. | |
func throw(r R, err error) R { | |
if err != nil { | |
panic(err) | |
} | |
return r | |
} | |
// | |
func DoStuff() (R, error) { | |
return "great", nil | |
} | |
// | |
func FailThings() (R, error) { | |
return "", Failure("FailThings", func() { | |
log.Printf("handled") | |
}) | |
} | |
// | |
func main() { | |
catch(DoStuff()) // No error. Nothing logged. | |
throw(DoStuff()) // No error. Nothing thrown. | |
catch(FailThings()) // Errors so catch prints the error which calls the callback. | |
throw(FailThings()) // Errors so throw panics after the callback. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment