Replies: 2 comments
-
|
Idk exactly what you mean by "globally," but here's what I'm doing in my chi-based project. You can create an Like this: var (
// Generic
ErrNotFound = errors.New("resources not found")
ErrConflict = errors.New("resources already exists")
// ... more as you wish
)
type AppError struct {
Err error
Message string
Details map[string]string
Op string
Cause error
}
func (e *AppError) Error() string {
if e.Cause != nil {
return fmt.Sprintf("%s: %s: %s", e.Op, e.Message, e.Cause.Error())
}
return fmt.Sprintf("%s: %s", e.Op, e.Message)
}
func (e *AppError) Unwrap() error {
return e.Err
}
func NewAppError(op string, err error, message string) *AppError {
return &AppError{
Op: op,
Err: err,
Message: message,
}
}
// --- Constructor Helpers ---
func NewNotFoundError(op, message string) *AppError {
return &AppError{Err: ErrNotFound, Op: op, Message: message}
}Then, create a helper called func JSONMessage(w http.ResponseWriter, r *http.Request, status int, message string) {
writeJSON(w, r, status, SuccessResponse{
Success: true,
Message: message,
})
}
func JSONError(w http.ResponseWriter, r *http.Request, err error) {
ctx := r.Context()
requestID := requestid.GetRequestID(ctx)
// 1. Check for context errors first
if ctxErr := ctx.Err(); ctxErr != nil {
handleContextError(w, r, ctxErr, err, requestID)
return
}
// 2. Check for domain.AppError
var appErr *domain.AppError
if errors.As(err, &appErr) {
handleAppError(w, r, appErr, requestID)
return
}
// 3. Check for context errors in the error chain
// Sometimes the context error is wrapped inside the original error
if errors.Is(err, context.DeadlineExceeded) {
handleContextError(w, r, context.DeadlineExceeded, err, requestID)
return
}
if errors.Is(err, context.Canceled) {
handleContextError(w, r, context.Canceled, err, requestID)
return
}
// 4. Unknown/Unexpected error
handleUnknownError(w, r, err, requestID)
}Now, if you're following the handler, service, and repo pattern, you can throw errors from your repo or services, catch them in the handler. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
What is a good pattern to return errors from handlers and handle them in a centralized place?
Beta Was this translation helpful? Give feedback.
All reactions