Exit an Application, With or Without an Error Code
·
257 words
·
2 minutes read
Exiting an application in Go happens anyway when the main()
function is complete, but the purpose of this post is to show you how to force that to happen. Perhaps at an earlier stage than the end of your code, perhaps with an error code too. This is a well established method in POSIX systems, whereby a program can return a 0-255 integer to indicate if the program ran successfully, and if not, why not.
We’ll be using the os
package in stdlib to exit for us. First we’ll look at exiting the application successfully (just below), then we’ll look at exiting with an error code.
Exit Successfully
|
|
Exit with Error (Status 1+)
Specifying an exit code above zero usually means an error has occurred. There is a list of common/reserved exit codes for bash to keep an eye on, but in our example below we will just be using our generic error code of 1.
Some common codes:
Code | Meaning |
---|---|
1 | General error |
2 | Misuse of shell builtins |
127 | Command not found |
128 | Fatal error signal |
130 | Ctrl+C termination |
|
|