Skip to content

Commit a41ce8b

Browse files
Merge pull request #3 from mittwald/feature/error-code-mapping
feat: add library code for mapping HTTP response errors onto specific error types
2 parents 0052251 + 6a715e8 commit a41ce8b

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

pkg/httperr/from_response.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package httperr
2+
3+
import "net/http"
4+
5+
// ErrFromResponse maps an HTTP response (with an error status code) to a (more
6+
// or less) specific error type.
7+
func ErrFromResponse(res *http.Response) error {
8+
switch res.StatusCode {
9+
case http.StatusNotFound:
10+
return &ErrNotFound{Response: res}
11+
case http.StatusForbidden:
12+
return &ErrPermissionDenied{Response: res}
13+
default:
14+
return &ErrUnexpectedResponse{Response: res}
15+
}
16+
}

pkg/httperr/not_found_error.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package httperr
2+
3+
import (
4+
"fmt"
5+
"net/http"
6+
)
7+
8+
// ErrNotFound represents the error of trying to access a resource that does
9+
// not exist.
10+
type ErrNotFound struct {
11+
Response *http.Response
12+
}
13+
14+
func (e *ErrNotFound) Error() string {
15+
return fmt.Sprintf("resource not found: %s", e.Response.Request.URL)
16+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package httperr
2+
3+
import (
4+
"fmt"
5+
"net/http"
6+
)
7+
8+
// ErrPermissionDenied represents the error of trying to access a resource that
9+
// the currently authenticated user is not authorized to access.
10+
type ErrPermissionDenied struct {
11+
Response *http.Response
12+
}
13+
14+
func (e *ErrPermissionDenied) Error() string {
15+
return fmt.Sprintf("permission to resource denied: %s", e.Response.Request.URL)
16+
}

0 commit comments

Comments
 (0)