Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit with error code in go?

What's the idiomatic way to exit a program with some error code?

The documentation for Exit says "The program terminates immediately; deferred functions are not run.", and log.Fatal just calls Exit. For things that aren't heinous errors, terminating the program without running deferred functions seems extreme.

Am I supposed to pass around some state that indicate that there's been an error, and then call Exit(1) at some point where I know that I can exit safely, with all deferred functions having been run?

like image 811
dan Avatar asked Sep 23 '13 16:09

dan


People also ask

What is err != Nil in Golang?

if err != nil { return err } > is outweighed by the value of deliberately handling each failure condition at the point at which they occur. Key to this is the cultural value of handling each and every error explicitly.

What is exit status 2 in Golang?

Exit code 2 is supposed to mean 'incorrect arguments' in the Unix tradition. Something like 127 or 255 would be better. -rob. -- You received this message because you are subscribed to the Google Groups "golang-nuts" group.


2 Answers

I do something along these lines in most of my real main packages, so that the return err convention is adopted as soon as possible, and has a proper termination:

func main() {     if err := run(); err != nil {         fmt.Fprintf(os.Stderr, "error: %v\n", err)         os.Exit(1)     } }  func run() error {     err := something()     if err != nil {         return err     }     // etc } 
like image 139
Gustavo Niemeyer Avatar answered Oct 23 '22 10:10

Gustavo Niemeyer


In python I commonly use pattern which converted to go looks like this:

func run() int {     // here goes     // the code      return 1 }  func main() {     os.Exit(run()) } 
like image 37
user2424794 Avatar answered Oct 23 '22 10:10

user2424794