Improved error handling
This commit is contained in:
parent
3d7bd89b39
commit
d3c9ee3ac6
3 changed files with 33 additions and 8 deletions
26
Context.go
26
Context.go
|
@ -1,6 +1,7 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"unsafe"
|
||||
|
@ -12,8 +13,9 @@ const maxParams = 16
|
|||
// Context represents the interface for a request & response context.
|
||||
type Context interface {
|
||||
Bytes([]byte) error
|
||||
Error(int, error) error
|
||||
Error(status int, messages ...any) error
|
||||
Reader(io.Reader) error
|
||||
SetStatus(status int)
|
||||
String(string) error
|
||||
}
|
||||
|
||||
|
@ -42,9 +44,20 @@ func (ctx *context) Bytes(body []byte) error {
|
|||
}
|
||||
|
||||
// Error is used for sending error messages to the client.
|
||||
func (ctx *context) Error(status int, err error) error {
|
||||
ctx.response.WriteHeader(status)
|
||||
return err
|
||||
func (ctx *context) Error(status int, messages ...any) error {
|
||||
var combined []error
|
||||
|
||||
for _, msg := range messages {
|
||||
switch err := msg.(type) {
|
||||
case error:
|
||||
combined = append(combined, err)
|
||||
case string:
|
||||
combined = append(combined, errors.New(err))
|
||||
}
|
||||
}
|
||||
|
||||
ctx.SetStatus(status)
|
||||
return errors.Join(combined...)
|
||||
}
|
||||
|
||||
// Reader sends the contents of the io.Reader without creating an in-memory copy.
|
||||
|
@ -53,6 +66,11 @@ func (ctx *context) Reader(reader io.Reader) error {
|
|||
return err
|
||||
}
|
||||
|
||||
// SetStatus writes the header with the given HTTP status code.
|
||||
func (ctx *context) SetStatus(status int) {
|
||||
ctx.response.WriteHeader(status)
|
||||
}
|
||||
|
||||
// String responds with the given string.
|
||||
func (ctx *context) String(body string) error {
|
||||
slice := unsafe.Slice(unsafe.StringData(body), len(body))
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue