Created
October 3, 2016 14:52
-
-
Save zgiber/0f1122f853e49996a8fd61f908453f35 to your computer and use it in GitHub Desktop.
custom error type adding some extras over standard error interface
This file contains hidden or 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
type customError struct { | |
statusCode int | |
description string | |
details interface{} | |
} | |
type CustomError interface { | |
error | |
StatusCode() int | |
Details() interface{} | |
WithStatus(int) CustomError | |
WithDetails(interface{}) CustomError | |
} | |
func New(description string) CustomError { | |
return customError{description: description} | |
} | |
func (err customError) Error() string { | |
return err.description | |
} | |
func (err customError) StatusCode() int { | |
return err.statusCode | |
} | |
func (err customError) Details() interface{} { | |
return err.Details | |
} | |
func (err customError) WithStatus(statusCode int) CustomError { | |
err.statusCode = statusCode | |
return err | |
} | |
func (err customError) WithDetails(details interface{}) CustomError { | |
err.details = details | |
return err | |
} | |
func (err *customError) MarshalJSON() ([]byte, error) { | |
res := struct { | |
StatusCode int `json:"status_code"` | |
Description string `json:"description"` | |
Details interface{} `json:"details,omitempty"` | |
}{ | |
err.statusCode, | |
err.description, | |
err.details, | |
} | |
return json.Marshal(res) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment