rc: factor rc.Error out of rcserver for re-use in librclone #4891
This commit is contained in:
parent
20c5ca08fb
commit
60bc7a079a
2 changed files with 25 additions and 14 deletions
|
@ -279,3 +279,26 @@ func (p Params) GetDuration(key string) (time.Duration, error) {
|
||||||
}
|
}
|
||||||
return duration, nil
|
return duration, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Error creates the standard response for an errored rc call using an
|
||||||
|
// rc.Param from a path, input Params, error and a suggested HTTP
|
||||||
|
// response code.
|
||||||
|
//
|
||||||
|
// It returns a Params and an updated status code
|
||||||
|
func Error(path string, in Params, err error, status int) (Params, int) {
|
||||||
|
// Adjust the status code for some well known errors
|
||||||
|
errOrig := errors.Cause(err)
|
||||||
|
switch {
|
||||||
|
case errOrig == fs.ErrorDirNotFound || errOrig == fs.ErrorObjectNotFound:
|
||||||
|
status = http.StatusNotFound
|
||||||
|
case IsErrParamInvalid(err) || IsErrParamNotFound(err):
|
||||||
|
status = http.StatusBadRequest
|
||||||
|
}
|
||||||
|
result := Params{
|
||||||
|
"status": status,
|
||||||
|
"error": err.Error(),
|
||||||
|
"input": in,
|
||||||
|
"path": path,
|
||||||
|
}
|
||||||
|
return result, status
|
||||||
|
}
|
||||||
|
|
|
@ -169,21 +169,9 @@ func (s *Server) Serve() error {
|
||||||
// writeError writes a formatted error to the output
|
// writeError writes a formatted error to the output
|
||||||
func writeError(path string, in rc.Params, w http.ResponseWriter, err error, status int) {
|
func writeError(path string, in rc.Params, w http.ResponseWriter, err error, status int) {
|
||||||
fs.Errorf(nil, "rc: %q: error: %v", path, err)
|
fs.Errorf(nil, "rc: %q: error: %v", path, err)
|
||||||
// Adjust the error return for some well known errors
|
params, status := rc.Error(path, in, err, status)
|
||||||
errOrig := errors.Cause(err)
|
|
||||||
switch {
|
|
||||||
case errOrig == fs.ErrorDirNotFound || errOrig == fs.ErrorObjectNotFound:
|
|
||||||
status = http.StatusNotFound
|
|
||||||
case rc.IsErrParamInvalid(err) || rc.IsErrParamNotFound(err):
|
|
||||||
status = http.StatusBadRequest
|
|
||||||
}
|
|
||||||
w.WriteHeader(status)
|
w.WriteHeader(status)
|
||||||
err = rc.WriteJSON(w, rc.Params{
|
err = rc.WriteJSON(w, params)
|
||||||
"status": status,
|
|
||||||
"error": err.Error(),
|
|
||||||
"input": in,
|
|
||||||
"path": path,
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// can't return the error at this point
|
// can't return the error at this point
|
||||||
fs.Errorf(nil, "rc: writeError: failed to write JSON output from %#v: %v", in, err)
|
fs.Errorf(nil, "rc: writeError: failed to write JSON output from %#v: %v", in, err)
|
||||||
|
|
Loading…
Add table
Reference in a new issue