github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/errors/doc.go (about) 1 /* 2 Package errors implements a basic error wrapping pattern, so that errors can be 3 annotated with additional information without losing the original error. 4 5 Example: 6 7 import "chain/errors" 8 9 func query() error { 10 err := pq.Exec("SELECT...") 11 if err != nil { 12 return errors.Wrap(err, "select query failed") 13 } 14 15 err = pq.Exec("INSERT...") 16 if err != nil { 17 return errors.Wrap(err, "insert query failed") 18 } 19 20 return nil 21 } 22 23 func main() { 24 err := query() 25 if _, ok := errors.Root(err).(sql.ErrNoRows); ok { 26 log.Println("There were no results") 27 return 28 } else if err != nil { 29 log.Println(err) 30 return 31 } 32 33 log.Println("success") 34 } 35 36 When to wrap errors 37 38 Errors should be wrapped with additional messages when the context is ambiguous. 39 This includes when the error could arise in multiple locations in the same 40 function, when the error is very common and likely to appear at different points 41 in the call tree (e.g., JSON serialization errors), or when you need specific 42 parameters alongside the original error message. 43 44 Error handling best practices 45 46 Errors are part of a function's interface. If you expect the caller to perform 47 conditional error handling, you should document the errors returned by your 48 function in a function comment, and include it as part of your unit tests. 49 50 Be disciplined about validating user input. Programs should draw a very clear 51 distinction between user errors and internal errors. 52 53 Avoid redundant error logging. If you return an error, assume it will be logged 54 higher up the call stack. For a given project, choose an appropriate layer to 55 handle error logging. 56 */ 57 package errors