From 1c8a68bbcb0e841d12c2b89ebfe976192e2f0c5d Mon Sep 17 00:00:00 2001 From: Aneurin Barker Snook Date: Fri, 13 Oct 2023 17:24:51 +0100 Subject: [PATCH] add simplified error writing --- body.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/body.go b/body.go index 3c17a6e..269434f 100644 --- a/body.go +++ b/body.go @@ -2,6 +2,7 @@ package rest import ( "encoding/json" + "errors" "io" "net/http" ) @@ -15,6 +16,28 @@ func ReadRequestJSON(req *http.Request, v any) error { return json.Unmarshal(data, v) } +// WriteError writes an error to an HTTP response. +// If the error is a REST API error, it is written as standard per Error.Write. +// Otherwise, ErrInternalServerError is written with the given error attached as data. +func WriteError(w http.ResponseWriter, err error) error { + if errors.Is(err, Err) { + _, ret := err.(Error).Write(w) + return ret + } + _, ret := ErrInternalServerError.WithError(err).Write(w) + return ret +} + +// WriteErrorJSON writes an error as JSON to an HTTP response. +// If the error is a REST API error, it is written as standard per Error.WriteJSON. +// Otherwise, ErrInternalServerError is written with the given error attached as data. +func WriteErrorJSON(w http.ResponseWriter, err error) error { + if errors.Is(err, Err) { + return err.(Error).WriteJSON(w) + } + return ErrInternalServerError.WithError(err).WriteJSON(w) +} + // WriteResponseJSON writes an HTTP response as JSON. func WriteResponseJSON(w http.ResponseWriter, statusCode int, data any) error { b, err := json.Marshal(data)