Basics of error handling:
https://codeeval.dev/gist/646f2e936bff82f90b7fbc62f891bf3c
Unlike languages like C# or Python, Go handles failures by returning error values, not raising exceptions.
Go also provides exceptions with panic and recover but they should be used rarely.
Errors are values, just like integers or string.
Type error
is a built-in interface which implements Error() string
method.
To indicate success, return nil
.
To create an error you can use standard library functions errors.New(msg string)
or fmt.Errorf(format string, args... interface{})
.
You can also return custom error types by defining structs that implement Error() string
method.
If a function returns an error, it should always be the last returned value.
Always check returned errors. A key to writing robust software is checking errors and handling them appropriately. Beginners often fail to check for errors and are then are faced with debugging mysterious failures.
Creating standard error values
Handling errors in short programs