Best Practices Error Handling #424
-
Hi Community, |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I would typically handle this at the operation handler, converting as you need after bubbling up any of the internal errors without translation. It's a bit of extra work but makes the code very easy to reason about / maintain and explicitly converts between the layers. Something like: func MyHandler(ctx context.Context, input *MyInput) (*MyOutput, error) {
result, err := db.Get("some query")
if errors.Is(err, db.ErrorNotFound) {
slog.ErrorContext(ctx, "Not found", "err", err, "id", input.ID)
return nil, huma.Error404NotFound("Thing with ID " + input.ID + " not found")
}
if errors.Is(err, db.ConnectionReset) {
slog.ErrorContext(ctx, "Can't talk to the DB", "err", err, "id", input.ID)
return nil, huma.Error500InternalServerError("Unable to reach DB, please try again later")
}
// Otherwise it's the happy path
return &MyOutput{Body: /* ... */}, nil
} |
Beta Was this translation helpful? Give feedback.
I would typically handle this at the operation handler, converting as you need after bubbling up any of the internal errors without translation. It's a bit of extra work but makes the code very easy to reason about / maintain and explicitly converts between the layers. Something like: