This repository was archived by the owner on Feb 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy patherror.go
93 lines (77 loc) · 2.16 KB
/
error.go
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
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright 2015 The Tango Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tango
import (
"fmt"
"net/http"
)
// AbortError defines an interface to describe HTTP error
type AbortError interface {
error
Code() int
}
type abortError struct {
code int
content string
}
func (a *abortError) Code() int {
return a.code
}
func (a *abortError) Error() string {
return fmt.Sprintf("%v", a.content)
}
// Abort returns an AbortError
func Abort(code int, content ...string) AbortError {
if len(content) >= 1 {
return &abortError{code, content[0]}
}
return &abortError{code, http.StatusText(code)}
}
// NotFound returns not found HTTP error
func NotFound(content ...string) AbortError {
return Abort(http.StatusNotFound, content...)
}
// NotSupported returns not supported HTTP error
func NotSupported(content ...string) AbortError {
return Abort(http.StatusMethodNotAllowed, content...)
}
// InternalServerError returns internal server HTTP error
func InternalServerError(content ...string) AbortError {
return Abort(http.StatusInternalServerError, content...)
}
// Forbidden returns forbidden HTTP error
func Forbidden(content ...string) AbortError {
return Abort(http.StatusForbidden, content...)
}
// Unauthorized returns unauthorized HTTP error
func Unauthorized(content ...string) AbortError {
return Abort(http.StatusUnauthorized, content...)
}
// Errors returns default errorhandler, you can use your self handler
func Errors() HandlerFunc {
return func(ctx *Context) {
switch res := ctx.Result.(type) {
case AbortError:
ctx.WriteHeader(res.Code())
ctx.WriteString(res.Error())
case error:
ctx.WriteHeader(http.StatusInternalServerError)
ctx.WriteString(res.Error())
default:
ctx.WriteHeader(http.StatusInternalServerError)
ctx.WriteString(http.StatusText(http.StatusInternalServerError))
}
}
}
// ErrorWithCode descripts an error that with error code
type ErrorWithCode interface {
error
ErrorCode() int
}
type ErrorKeyIsNotExist struct {
Key string
}
func (e ErrorKeyIsNotExist) Error() string {
return fmt.Sprintf("Key %s is not exist", e.Key)
}