Skip to content

Commit

Permalink
feat: add library code for mapping HTTP response errors onto specific…
Browse files Browse the repository at this point in the history
… error types
  • Loading branch information
martin-helmich committed Jan 24, 2025
1 parent 0052251 commit 6a715e8
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
16 changes: 16 additions & 0 deletions pkg/httperr/from_response.go
Original file line number Diff line number Diff line change
@@ -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}
}
}
16 changes: 16 additions & 0 deletions pkg/httperr/not_found_error.go
Original file line number Diff line number Diff line change
@@ -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)
}
16 changes: 16 additions & 0 deletions pkg/httperr/permission_denied_error.go
Original file line number Diff line number Diff line change
@@ -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)
}

0 comments on commit 6a715e8

Please sign in to comment.