forked from objenious/errorutil
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_test.go
More file actions
80 lines (69 loc) · 2.22 KB
/
http_test.go
File metadata and controls
80 lines (69 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package errorutil
import (
"database/sql"
"errors"
"net/http"
"os"
"testing"
pkgerrors "github.com/pkg/errors"
)
func TestHTTPStatusCode(t *testing.T) {
tests := []struct {
err error
want int
}{
{nil, http.StatusOK},
{errors.New("foo"), http.StatusInternalServerError},
{os.ErrNotExist, http.StatusNotFound},
{pkgerrors.Wrap(os.ErrNotExist, "bar"), http.StatusNotFound},
{os.ErrPermission, http.StatusForbidden},
{pkgerrors.Wrap(os.ErrPermission, "bar"), http.StatusForbidden},
{sql.ErrNoRows, http.StatusNotFound},
{pkgerrors.Wrap(sql.ErrNoRows, "bar"), http.StatusNotFound},
{httpError(http.StatusNotFound), http.StatusNotFound},
{pkgerrors.Wrap(httpError(http.StatusNotFound), "bar"), http.StatusNotFound},
{httpError(http.StatusForbidden), http.StatusForbidden},
{pkgerrors.Wrap(httpError(http.StatusForbidden), "bar"), http.StatusForbidden},
{NotFoundError(errors.New("foo")), http.StatusNotFound},
{pkgerrors.Wrap(NotFoundError(errors.New("foo")), "bar"), http.StatusNotFound},
{ForbiddenError(errors.New("foo")), http.StatusForbidden},
{pkgerrors.Wrap(ForbiddenError(errors.New("foo")), "bar"), http.StatusForbidden},
{InvalidError(errors.New("foo")), http.StatusBadRequest},
{pkgerrors.Wrap(InvalidError(errors.New("foo")), "bar"), http.StatusBadRequest},
}
for _, tt := range tests {
got := HTTPStatusCode(tt.err)
if got != tt.want {
t.Errorf("HTTPStatusCode(%q): got: %v, want %v", tt.err, got, tt.want)
}
}
}
func ExampleHTTPError() {
resp, err := http.Get("http://www.example.com")
if err != nil {
// return error
}
defer resp.Body.Close()
if err := HTTPError(resp); err != nil {
// return error
}
// handle response
}
func ExampleNotFoundError() {
var w http.ResponseWriter
err := errors.New("some error")
err = NotFoundError(err)
w.WriteHeader(HTTPStatusCode(err)) // returns http.StatusNotFound
}
func ExampleForbiddenError() {
var w http.ResponseWriter
err := errors.New("some error")
err = ForbiddenError(err)
w.WriteHeader(HTTPStatusCode(err)) // returns http.StatusForbidden
}
func ExampleInvalidError() {
var w http.ResponseWriter
err := errors.New("some error")
err = InvalidError(err)
w.WriteHeader(HTTPStatusCode(err)) // returns http.StatusBadRequest
}