forked from rs/rest-layer
/
errors.go
77 lines (71 loc) · 2.66 KB
/
errors.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
package rest
import (
"context"
"net/http"
"github.com/rs/rest-layer/resource"
)
var (
// ErrNotFound represents a 404 HTTP error.
ErrNotFound = &Error{http.StatusNotFound, "Not Found", nil}
// ErrUnauthorized represents a 401 HTTP error.
ErrUnauthorized = &Error{http.StatusUnauthorized, "Unauthorized", nil}
// ErrPreconditionFailed happens when a conditional request condition is not met.
ErrPreconditionFailed = &Error{http.StatusPreconditionFailed, "Precondition Failed", nil}
// ErrConflict happens when another thread or node modified the data concurrently
// with our own thread in such a way we can't securely apply the requested changes.
ErrConflict = &Error{http.StatusConflict, "Conflict", nil}
// ErrInvalidMethod happens when the used HTTP method is not supported for this
// resource.
ErrInvalidMethod = &Error{http.StatusMethodNotAllowed, "Invalid Method", nil}
// ErrClientClosedRequest is returned when the client closed the connection before
// the server was able to finish processing the request.
ErrClientClosedRequest = &Error{499, "Client Closed Request", nil}
// ErrNotImplemented happens when a requested feature is not implemented.
ErrNotImplemented = &Error{http.StatusNotImplemented, "Not Implemented", nil}
// ErrGatewayTimeout is returned when the specified timeout for the request has been
// reached before the server was able to process it.
ErrGatewayTimeout = &Error{http.StatusGatewayTimeout, "Deadline Exceeded", nil}
// ErrUnknown is thrown when the origine of the error can't be identified.
ErrUnknown = &Error{520, "Unknown Error", nil}
)
// Error defines a REST error with optional per fields error details
type Error struct {
// Code defines the error code to be used for the error and for the HTTP status
Code int
// Message is the error message
Message string
// Issues holds per fields errors if any
Issues map[string][]interface{}
}
// NewError returns a rest.Error from an standard error.
//
// If the the inputed error is recognized, the appropriate rest.Error is mapped.
func NewError(err error) *Error {
if Err, ok := err.(*Error); ok {
return Err
}
switch err {
case context.Canceled:
return ErrClientClosedRequest
case context.DeadlineExceeded:
return ErrGatewayTimeout
case resource.ErrNotFound:
return ErrNotFound
case resource.ErrUnauthorized:
return ErrUnauthorized
case resource.ErrConflict:
return ErrConflict
case resource.ErrNotImplemented:
return ErrNotImplemented
case resource.ErrNoStorage:
return &Error{501, err.Error(), nil}
case nil:
return nil
default:
return &Error{520, err.Error(), nil}
}
}
// Error returns the error as string
func (e *Error) Error() string {
return e.Message
}