Skip to content

Instantly share code, notes, and snippets.

@abdivasiyev
Created April 25, 2025 06:05
Show Gist options
  • Save abdivasiyev/3b37637d8abe4e7a12a12e38c819814f to your computer and use it in GitHub Desktop.
Save abdivasiyev/3b37637d8abe4e7a12a12e38c819814f to your computer and use it in GitHub Desktop.
Custom error struct for Go apps
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