소스 검색

add simplified error writing

Aneurin Barker Snook 1 년 전
부모
커밋
1c8a68bbcb
1개의 변경된 파일23개의 추가작업 그리고 0개의 파일을 삭제
  1. 23 0
      body.go

+ 23 - 0
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)