main.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "dy-pkg/errors"
  6. )
  7. const (
  8. ErrDatabase = iota + 100000
  9. ErrEncodingFailed
  10. )
  11. func init() {
  12. errors.RegisterCode(ErrDatabase, http.StatusInternalServerError, "数据错误", "")
  13. errors.RegisterCode(ErrEncodingFailed, http.StatusInternalServerError, "绑定错误", "")
  14. }
  15. func main() {
  16. if err := bindUser(); err != nil {
  17. // %s: Returns the user-safe error string mapped to the error code or the error message if none is specified.
  18. fmt.Println("====================> %s <====================")
  19. fmt.Printf("%s\n\n", err)
  20. // %v: Alias for %s.
  21. fmt.Println("====================> %v <====================")
  22. fmt.Printf("%v\n\n", err)
  23. //
  24. // %-v: Output caller details, useful for troubleshooting.
  25. fmt.Println("====================> %-v <====================")
  26. fmt.Printf("%-v\n\n", err)
  27. //
  28. // %+v: Output full error stack details, useful for debugging.
  29. fmt.Println("====================> %+v <====================")
  30. fmt.Printf("%+v\n\n", err)
  31. //
  32. // %#-v: Output caller details, useful for troubleshooting with JSON formatted output.
  33. fmt.Println("====================> %#-v <====================")
  34. fmt.Printf("%#-v\n\n", err)
  35. //
  36. // %#+v: Output full error stack details, useful for debugging with JSON formatted output.
  37. fmt.Println("====================> %#+v <====================")
  38. fmt.Printf("%#+v\n\n", err)
  39. //
  40. // do some business process based on the error type
  41. if errors.IsCode(err, ErrEncodingFailed) {
  42. fmt.Println("this is a ErrEncodingFailed error")
  43. }
  44. //
  45. if errors.IsCode(err, ErrDatabase) {
  46. fmt.Println("this is a ErrDatabase error")
  47. }
  48. // we can also find the cause error
  49. fmt.Println(errors.Cause(err))
  50. }
  51. }
  52. func bindUser() error {
  53. if err := getUser(); err != nil {
  54. // Step3: Wrap the error with a new error message and a new error code if needed.
  55. return errors.WrapC(err, ErrEncodingFailed, "encoding user 'Lingfei Kong' failed.")
  56. }
  57. return nil
  58. }
  59. func getUser() error {
  60. if err := queryDatabase(); err != nil {
  61. // Step2: Wrap the error with a new error message.
  62. return errors.Wrap(err, "get user failed.")
  63. }
  64. return nil
  65. }
  66. func queryDatabase() error {
  67. // Step1. Create error with specified error code.
  68. return errors.WithCode(ErrDatabase, "user 'Lingfei Kong' not found.")
  69. }