From 6a715e809e15def425d9f2b8235d67ce82f3a39c Mon Sep 17 00:00:00 2001 From: Martin Helmich Date: Fri, 24 Jan 2025 12:54:23 +0100 Subject: [PATCH] feat: add library code for mapping HTTP response errors onto specific error types --- pkg/httperr/from_response.go | 16 ++++++++++++++++ pkg/httperr/not_found_error.go | 16 ++++++++++++++++ pkg/httperr/permission_denied_error.go | 16 ++++++++++++++++ 3 files changed, 48 insertions(+) create mode 100644 pkg/httperr/from_response.go create mode 100644 pkg/httperr/not_found_error.go create mode 100644 pkg/httperr/permission_denied_error.go diff --git a/pkg/httperr/from_response.go b/pkg/httperr/from_response.go new file mode 100644 index 0000000..4948f9e --- /dev/null +++ b/pkg/httperr/from_response.go @@ -0,0 +1,16 @@ +package httperr + +import "net/http" + +// ErrFromResponse maps an HTTP response (with an error status code) to a (more +// or less) specific error type. +func ErrFromResponse(res *http.Response) error { + switch res.StatusCode { + case http.StatusNotFound: + return &ErrNotFound{Response: res} + case http.StatusForbidden: + return &ErrPermissionDenied{Response: res} + default: + return &ErrUnexpectedResponse{Response: res} + } +} diff --git a/pkg/httperr/not_found_error.go b/pkg/httperr/not_found_error.go new file mode 100644 index 0000000..2ceaabc --- /dev/null +++ b/pkg/httperr/not_found_error.go @@ -0,0 +1,16 @@ +package httperr + +import ( + "fmt" + "net/http" +) + +// ErrNotFound represents the error of trying to access a resource that does +// not exist. +type ErrNotFound struct { + Response *http.Response +} + +func (e *ErrNotFound) Error() string { + return fmt.Sprintf("resource not found: %s", e.Response.Request.URL) +} diff --git a/pkg/httperr/permission_denied_error.go b/pkg/httperr/permission_denied_error.go new file mode 100644 index 0000000..fa0a211 --- /dev/null +++ b/pkg/httperr/permission_denied_error.go @@ -0,0 +1,16 @@ +package httperr + +import ( + "fmt" + "net/http" +) + +// ErrPermissionDenied represents the error of trying to access a resource that +// the currently authenticated user is not authorized to access. +type ErrPermissionDenied struct { + Response *http.Response +} + +func (e *ErrPermissionDenied) Error() string { + return fmt.Sprintf("permission to resource denied: %s", e.Response.Request.URL) +}