forked from TrueCloudLab/rclone
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
|
||||
}
|
||||
|
||||
// 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
|
||||
func writeError(path string, in rc.Params, w http.ResponseWriter, err error, status int) {
|
||||
fs.Errorf(nil, "rc: %q: error: %v", path, err)
|
||||
// Adjust the error return for some well known errors
|
||||
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
|
||||
}
|
||||
params, status := rc.Error(path, in, err, status)
|
||||
w.WriteHeader(status)
|
||||
err = rc.WriteJSON(w, rc.Params{
|
||||
"status": status,
|
||||
"error": err.Error(),
|
||||
"input": in,
|
||||
"path": path,
|
||||
})
|
||||
err = rc.WriteJSON(w, params)
|
||||
if err != nil {
|
||||
// can't return the error at this point
|
||||
fs.Errorf(nil, "rc: writeError: failed to write JSON output from %#v: %v", in, err)
|
||||
|
|
Loading…
Reference in a new issue