Skip to content

Commit

Permalink
Merge pull request #3 from mittwald/feature/error-code-mapping
Browse files Browse the repository at this point in the history
feat: add library code for mapping HTTP response errors onto specific error types
  • Loading branch information
martin-helmich authored Jan 24, 2025
2 parents 0052251 + 6a715e8 commit a41ce8b
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 a41ce8b

Please sign in to comment.