Skip to content

Latest commit

 

History

History
 
 

07-error_handling

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Error Handling

Error handling is critical for making your programs reliable, trustworthy and respectful to those who depend on them. A proper error value is both specific and informative. It must allow the caller to make an informed decision about the error that has occurred. There are several ways in Go to create error values. This depends on the amount of context that needs to be provided.

Notes

  • Use the default error value for static and simple formatted messages.
  • Create and return error variables to help the caller identify specific errors.
  • Create custom error types when the context of the error is more complex.
  • Error Values in Go aren't special, they are just values like any other, and so you have the entire language at your disposal.

Links

http:https://blog.golang.org/error-handling-and-go

http:https://www.goinggo.net/2014/10/error-handling-in-go-part-i.html

http:https://www.goinggo.net/2014/11/error-handling-in-go-part-ii.html

http:https://clipperhouse.com/2015/02/07/bugs-are-a-failure-of-prediction/

http:https://dave.cheney.net/2014/12/24/inspecting-errors

Code Review

Default Error Values (Go Playground)

Error Variables (Go Playground)

Type As Context (Go Playground)

Behavior As Context (Go Playground)

Find The Bug (Go Playground)

Exercises

Exercise 1

Create two error variables, one called ErrInvalidValue and the other called ErrAmountTooLarge. Provide the static message for each variable. Then write a function called checkAmount that accepts a float64 type value and returns an error value. Check the value for zero and if it is, return the ErrInvalidValue. Check the value for greater than $1,000 and if it is, return the ErrAmountTooLarge. Write a main function to call the checkAmount function and check the return error value. Display a proper message to the screen.

Template (Go Playground) | Answer (Go Playground)

Exercise 2

Create a custom error type called appError that contains three fields, Err error, Message string and Code int. Implement the error interface providing your own message using these three fields. Write a function called checkFlag that accepts a bool value. If the value is false, return a pointer of your custom error type initialized as you like. If the value is true, return a default error. Write a main function to call the checkFlag function and check the error for the concrete type.

Template (Go Playground) | Answer (Go Playground)


Ardan Labs Ardan Studios GoingGo Blog


All material is licensed under the GNU Free Documentation License.