github.com/alloyzeus/go-azfl@v0.0.0-20231220071816-9740126a2d07/azerrs/errors.go (about) 1 // Package errors provides extra functionalities to that of Go's stdlib 2 // errors package. 3 // 4 // An error as follow is informative for human developers: 5 // 6 // Unable to parse "example" as an email address. 7 // 8 // But for other part of code that calls the function, it will need to 9 // parse that message so that it can react properly, including to translate 10 // the message into various human languages. 11 // 12 // It is pretty much clear that structured errors are more flexible. For the 13 // calling routines, they won't need to parse the message. If we are going 14 // to display the error to human end users, the structured errors will also 15 // have more advantages as different human languages are constructed 16 // differently. 17 // 18 // Examples: 19 // 20 // // An error that describes that argument "username" is unspecified 21 // err := errors.Arg("username").Unspecified() 22 // 23 // // Check if an error is an argument error where "username" is unspecified 24 // errors.IsArgUnspecified(err, "username") 25 // 26 // // ... or simply check if it's an argument error 27 // if errors.IsArgumentError(err) { 28 // // e.g., respond with HTTP 400 29 // } 30 // 31 // // An error that describes that the field "Name" of entity with ID "user5432" is empty 32 // errors.Ent("user5432").Fieldset(errors.Ent("Name").Desc(errors.ErrValueEmpty)) 33 // 34 // // An error that describes that argument "email" is malformed. Detailing error, usually from 35 // // the parser function, is available as wrapped error. 36 // errors.Arg("email").Desc(errors.ErrValueMalformed).Wrap(err) 37 // 38 package errors 39 40 import ( 41 "errors" 42 ) 43 44 // Wraps Go's errors 45 var ( 46 As = errors.As 47 Is = errors.Is 48 New = errors.New // Prefer Msg instead as it has better semantic 49 Msg = errors.New 50 Unwrap = errors.Unwrap 51 ) 52 53 //TODO: fields. 54 // e.g., errors.Msg("error message", errors.Str("name", name), errors.Err(err)) 55 // or errors.With().Str("name", name).Err(err).Msg("error message") 56 // or errors.With().StrErr("name", nameErr).Msg("error message") 57 // (sounds like structured logging? exactly!) 58 59 const ( 60 // ErrUnimplemented is used to declare that a functionality, or part of it, 61 // has not been implemented. This could be well mapped to some protocols' 62 // status code, e.g., HTTP's 501 and gRPC's 12 . 63 ErrUnimplemented = constantErrorDescriptor("unimplemented") 64 ) 65 66 func errorString(err error) string { 67 if err != nil { 68 return err.Error() 69 } 70 return "" 71 }