s3manager-web/internal/app/s3manager/errors.go

51 lines
1.2 KiB
Go
Raw Normal View History

2017-05-08 23:07:07 +02:00
package s3manager
2017-04-09 16:28:57 +02:00
import (
2017-05-28 19:38:59 +02:00
"encoding/json"
"io"
2017-04-09 16:28:57 +02:00
"log"
"net/http"
2017-05-25 18:33:44 +02:00
"github.com/pkg/errors"
2017-04-09 16:28:57 +02:00
)
2017-05-25 18:33:44 +02:00
// Error codes commonly used throughout the application
2017-04-09 16:28:57 +02:00
const (
2017-05-25 18:33:44 +02:00
errDecodingBody = "error decoding body JSON"
errEncodingJSON = "error encoding JSON"
errExecutingTemplate = "error executing template"
errParsingForm = "error parsing form"
errParsingTemplates = "error parsing template files"
)
// Errors that may be returned from an S3 client.
var (
ErrBucketDoesNotExist = errors.New("The specified bucket does not exist.")
ErrKeyDoesNotExist = errors.New("The specified key does not exist.")
2017-04-09 16:28:57 +02:00
)
2017-05-08 23:07:07 +02:00
// handleHTTPError handles HTTP errors.
2017-05-25 18:33:44 +02:00
func handleHTTPError(w http.ResponseWriter, err error) {
2017-05-28 19:38:59 +02:00
var code int
2017-05-29 16:38:48 +02:00
2017-05-28 19:38:59 +02:00
switch err := errors.Cause(err).(type) {
case *json.SyntaxError:
2017-05-25 18:33:44 +02:00
code = http.StatusUnprocessableEntity
2017-05-28 19:38:59 +02:00
default:
2017-05-29 16:38:48 +02:00
if err == io.EOF || err == io.ErrUnexpectedEOF {
2017-05-28 19:38:59 +02:00
code = http.StatusUnprocessableEntity
2017-05-29 16:38:48 +02:00
} else if err == ErrBucketDoesNotExist || err == ErrKeyDoesNotExist {
2017-05-28 19:38:59 +02:00
code = http.StatusNotFound
} else {
code = http.StatusInternalServerError
}
2017-05-25 18:33:44 +02:00
}
http.Error(w, http.StatusText(code), code)
2017-04-09 16:28:57 +02:00
2017-05-25 18:33:44 +02:00
// Log if server error
if code >= 500 {
log.Println(err)
2017-04-09 16:28:57 +02:00
}
}