Skip to content

Instantly share code, notes, and snippets.

@zgiber
Created October 3, 2016 14:52
Show Gist options
  • Save zgiber/0f1122f853e49996a8fd61f908453f35 to your computer and use it in GitHub Desktop.
Save zgiber/0f1122f853e49996a8fd61f908453f35 to your computer and use it in GitHub Desktop.
custom error type adding some extras over standard error interface
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