Created
April 25, 2025 06:05
-
-
Save abdivasiyev/3b37637d8abe4e7a12a12e38c819814f to your computer and use it in GitHub Desktop.
Custom error struct for Go apps
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
package errorsx | |
import ( | |
"errors" | |
"fmt" | |
"net/http" | |
) | |
type AppError struct { | |
message string | |
code int | |
statusCode int | |
internal bool | |
} | |
func (e *AppError) Code() int { | |
return e.code | |
} | |
func (e *AppError) Message() string { | |
return e.message | |
} | |
func (e *AppError) StatusCode() int { | |
return e.statusCode | |
} | |
func (e *AppError) Internal() bool { | |
return e.internal | |
} | |
func (e *AppError) Error() string { | |
return fmt.Sprintf(`[%d] %s (internal=%t)`, e.code, e.message, e.internal) | |
} | |
func New() *AppError { | |
return &AppError{ | |
code: http.StatusOK, | |
message: http.StatusText(http.StatusOK), | |
statusCode: http.StatusOK, | |
internal: false, | |
} | |
} | |
func (e *AppError) WithCode(code int) *AppError { | |
e.code = code | |
return e | |
} | |
func (e *AppError) WithStatusCode(statusCode int) *AppError { | |
e.statusCode = statusCode | |
return e | |
} | |
func (e *AppError) WithMessage(message string) *AppError { | |
e.message = message | |
return e | |
} | |
func (e *AppError) WithInternal() *AppError { | |
e.internal = true | |
return e | |
} | |
func As(err error) (*AppError, bool) { | |
var errX *AppError | |
ok := errors.As(err, &errX) | |
if errX == nil { | |
return nil, false | |
} | |
return errX, ok | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment