Last active
August 29, 2015 14:03
-
-
Save taylortrimble/b8998793849b9e1fa436 to your computer and use it in GitHub Desktop.
Golang errors and such
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 main | |
// UserError contains error information presented to the users of our API | |
type UserError struct { | |
Msg string `json:"message"` | |
Code int `json:"error"` | |
} | |
// ApplicationError contains information about errors that arise while accessing resources. | |
type ApplicationError struct { | |
Msg string | |
Err error | |
Code int | |
} | |
// Error returns a human-readable representation of a ApplicationError. | |
func (err *ApplicationError) Error() string { | |
return err.Msg | |
} | |
// UserError return a user-facing error | |
func (rerr *ApplicationError) UserError() *UserError { | |
return &UserError{Msg: rerr.Msg, Code: rerr.Code} | |
} |
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
// Just an application error, like a user who doesn't have permission to create another admin. | |
if !currentUser.IsAdmin() && u.IsAdmin() { | |
return nil, &ApplicationError{Msg: "You must have admin privileges to create another admin user", Code: http.StatusForbidden} | |
} | |
// An actual error that occurs in our code. In this case, our crypto. | |
hash, herr := bcrypt.GenerateFromPassword([]byte(*u.Password), bcrypt.DefaultCost) | |
if herr != nil { | |
return nil, &ApplicationError{Msg: "An unknown internal error has occured. This issue will be automatically reported.", Err: herr, Code: http.StatusInternalServerError} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment