(w http.ResponseWriter, accept string, err error, options *RouteOptions)
| 121 | } |
| 122 | |
| 123 | func writeError(w http.ResponseWriter, accept string, err error, options *RouteOptions) { |
| 124 | var e Error |
| 125 | if !errors.As(err, &e) { |
| 126 | e = Error{ |
| 127 | Detail: err.Error(), |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | e.Source = extractErrorsSource(err) |
| 132 | |
| 133 | for statusError, s := range options.statusMap { |
| 134 | if errors.Is(err, statusError) { |
| 135 | e.Status = s |
| 136 | } |
| 137 | } |
| 138 | if e.Status == 0 { |
| 139 | e.Status = http.StatusInternalServerError |
| 140 | } |
| 141 | |
| 142 | e.Detail = err.Error() |
| 143 | |
| 144 | var bre badRequestError |
| 145 | if e.Code == errorCodeBadQArg || errors.As(err, &bre) { |
| 146 | e.Status = http.StatusBadRequest |
| 147 | } |
| 148 | |
| 149 | var nfe notFoundError |
| 150 | if e.Code == ErrorCodeNotFound || errors.As(err, &nfe) { |
| 151 | e.Status = http.StatusNotFound |
| 152 | } |
| 153 | |
| 154 | if errors.Is(err, encoding.ErrNoEncoderAvailable) { |
| 155 | e.Status = http.StatusNotAcceptable |
| 156 | e.Detail = fmt.Sprintf("Accept header cannot be satisfied: enabled content types for this route: %v", options.codecs.OrderedMimeTypes) |
| 157 | accept = strings.Join(options.codecs.Codecs[encoding.DefaultCodecKey].MimeTypes, "; ") |
| 158 | } |
| 159 | |
| 160 | // if no acceptable codec is chosen, we will write to the client in the default codec available. |
| 161 | // There should be one at least, otherwise it would have paniced when configuring the route options |
| 162 | // codecs. |
| 163 | if accept == "" { |
| 164 | accept = encoding.DefaultCodecKey |
| 165 | } |
| 166 | |
| 167 | encoder := encoding.AcceptEncoder(w, accept, encoding.EditOff, options.codecs) |
| 168 | |
| 169 | w.WriteHeader(e.Status) |
| 170 | err = encoder.Encode(e) |
| 171 | if err != nil { |
| 172 | // We can't do anything, we need to make the HTTP server intercept the panic |
| 173 | panic(err) |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | type notFoundError struct { |
| 178 | Resource string |
no test coverage detected