Attempts to map an error to an HTTP status code and message. Defaults to 500 if it doesn't recognize the error. Returns 200 for a nil error.
(err error)
| 115 | // Attempts to map an error to an HTTP status code and message. |
| 116 | // Defaults to 500 if it doesn't recognize the error. Returns 200 for a nil error. |
| 117 | func ErrorAsHTTPStatus(err error) (int, string) { |
| 118 | if err == nil { |
| 119 | return 200, "OK" |
| 120 | } |
| 121 | |
| 122 | unwrappedErr := pkgerrors.Cause(err) |
| 123 | |
| 124 | // Check for SGErrors |
| 125 | switch unwrappedErr { |
| 126 | case gocb.ErrDocumentNotFound, ErrNotFound: |
| 127 | return http.StatusNotFound, "missing" |
| 128 | case gocb.ErrDocumentExists, ErrAlreadyExists: |
| 129 | return http.StatusConflict, "Conflict" |
| 130 | case gocb.ErrTimeout: |
| 131 | return http.StatusServiceUnavailable, "Database timeout error (gocb.ErrTimeout)" |
| 132 | case gocb.ErrOverload: |
| 133 | return http.StatusServiceUnavailable, "Database server is over capacity (gocb.ErrOverload)" |
| 134 | case gocb.ErrTemporaryFailure: |
| 135 | return http.StatusServiceUnavailable, "Database server is over capacity (gocb.ErrTemporaryFailure)" |
| 136 | case gocb.ErrValueTooLarge: |
| 137 | return http.StatusRequestEntityTooLarge, "Document too large!" |
| 138 | case ErrViewTimeoutError: |
| 139 | return http.StatusServiceUnavailable, unwrappedErr.Error() |
| 140 | case ErrReplicationLimitExceeded: |
| 141 | return http.StatusServiceUnavailable, unwrappedErr.Error() |
| 142 | } |
| 143 | |
| 144 | // gocb V2 errors |
| 145 | if errors.Is(unwrappedErr, gocb.ErrDocumentNotFound) { |
| 146 | return http.StatusNotFound, "missing" |
| 147 | } |
| 148 | if errors.Is(unwrappedErr, gocb.ErrDocumentExists) { |
| 149 | return http.StatusConflict, "Conflict" |
| 150 | } |
| 151 | if errors.Is(unwrappedErr, gocb.ErrTimeout) { |
| 152 | return http.StatusServiceUnavailable, "Database timeout error (gocb.ErrTimeout)" |
| 153 | } |
| 154 | if isKVError(unwrappedErr, memd.StatusTooBig) { |
| 155 | return http.StatusRequestEntityTooLarge, "Document too large!" |
| 156 | } |
| 157 | |
| 158 | switch unwrappedErr := unwrappedErr.(type) { |
| 159 | case *HTTPError: |
| 160 | return unwrappedErr.Status, unwrappedErr.Message |
| 161 | case *gomemcached.MCResponse: |
| 162 | switch unwrappedErr.Status { |
| 163 | case gomemcached.KEY_ENOENT: |
| 164 | return http.StatusNotFound, "missing" |
| 165 | case gomemcached.KEY_EEXISTS: |
| 166 | return http.StatusConflict, "Conflict" |
| 167 | case gomemcached.E2BIG: |
| 168 | return http.StatusRequestEntityTooLarge, "Too Large: " + string(unwrappedErr.Body) |
| 169 | case gomemcached.TMPFAIL: |
| 170 | return http.StatusServiceUnavailable, "Database server is over capacity (gomemcached.TMPFAIL)" |
| 171 | default: |
| 172 | return http.StatusBadGateway, fmt.Sprintf("%s (%s)", |
| 173 | string(unwrappedErr.Body), unwrappedErr.Status.String()) |
| 174 | } |