[v4] support error handling flow like gRPC (#158)
Some checks failed
sync / sync (push) Failing after 1h5m56s
test / test (push) Failing after 1h9m11s
coverage / build (push) Failing after 1h9m22s

* add status package with tests and integrate into response parsing
* improve unit-tests
* improve readme
This commit is contained in:
2025-09-30 12:28:39 +05:00
committed by GitHub
parent 9bb2f8cffa
commit 6209a03044
7 changed files with 308 additions and 26 deletions

54
status/status.go Normal file
View File

@@ -0,0 +1,54 @@
package status
import (
"errors"
"fmt"
"net/http"
)
// Status represents the outcome of an HTTP request in a style similar to gRPC status.
type Status struct {
code int // HTTP status code
message string // HTTP status text
details any // parsed error object
}
func New(statusCode int) *Status {
return &Status{code: statusCode, message: http.StatusText(statusCode)}
}
func FromError(err error) (*Status, bool) {
if err == nil {
return nil, false
}
var e *Error
if errors.As(err, &e) {
return e.HTTPStatus(), true
}
return nil, false
}
func (s *Status) Code() int {
return s.code
}
func (s *Status) Message() string {
return s.message
}
func (s *Status) Details() any {
return s.details
}
func (s *Status) WithDetails(details any) *Status {
s.details = details
return s
}
func (s *Status) String() string {
return fmt.Sprintf("http error: code = %d desc = %s", s.Code(), s.Message())
}
func (s *Status) Err() error {
return &Error{s: s}
}