Last active
April 8, 2019 15:18
-
-
Save alexkappa/807d13e6cd6f5ac713d2918818e0df3b to your computer and use it in GitHub Desktop.
Auth0 Go SDK Error Type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Drew inspiration from this gist.