Skip to content

Instantly share code, notes, and snippets.

@alexkappa
Last active April 8, 2019 15:18
Show Gist options
  • Save alexkappa/807d13e6cd6f5ac713d2918818e0df3b to your computer and use it in GitHub Desktop.
Save alexkappa/807d13e6cd6f5ac713d2918818e0df3b to your computer and use it in GitHub Desktop.
Auth0 Go SDK Error Type
package management
type ErrorType int
const (
UnknownError ErrorType = iota
CannotSetUsernameForConnectionError
PasswordStrengthError
UsernameAlreadyInUse
ConnectionDoesNotExist
)
var toErrorType = map[string]ErrorType{
"Cannot set username for connection without requires_username": CannotSetUsernameForConnectionError,
"PasswordStrengthError: Password is too weak": PasswordStrengthError,
"The username provided is in use already.": UsernameAlreadyInUse,
"The connection does not exist.": ConnectionDoesNotExist,
}
type Error interface {
Status() int
error
}
type managementError struct {
StatusCode int `json:"statusCode"`
Err string `json:"error"`
Message string `json:"message"`
errType string `json:"-"`
}
func newError(r io.Reader) error {
m := &managementError{}
err := json.NewDecoder(r).Decode(m)
if err != nil {
return err
}
m.errType = toErrorType[m.Message] // if not found, defaults to zero value: UnknownError
return m
}
func (m *managementError) Error() string {
return fmt.Sprintf("%d %s: %s", m.StatusCode, m.Err, m.Message)
}
func (m *managementError) Status() int {
return m.StatusCode
}
func (m *managementError) Type() ErrorType {
return m.errType
}
if err := api.User.Create(u); err != nil {
switch err.(management.Error).Type() {
case management.UsernameAlreadyInUse:
// handle email already exists
case management.PasswordStrengthError:
// handle password strength error
}
}
@alexkappa
Copy link
Author

Drew inspiration from this gist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment