1
0
Fork 0
photos/internal/httphelpers/error.go

64 lines
1.6 KiB
Go
Raw Normal View History

2020-05-31 02:22:25 +08:00
package httphelpers
import (
"errors"
2020-06-14 18:40:55 +08:00
"fmt"
2020-05-31 02:22:25 +08:00
"net/http"
"github.com/minio/minio-go/v6"
)
var ErrorBadRequest = errors.New("bad request")
var ErrorMethodNotAllowed = errors.New("method not allowed")
2020-06-14 18:40:55 +08:00
var ErrorNotFound = errors.New("not found")
2020-08-23 00:21:56 +08:00
var ErrorUnauthorized = errors.New("unauthorized")
2020-05-31 02:22:25 +08:00
func ErrorResponse(w http.ResponseWriter, err error) {
if err == nil {
panic("Sneaky, you called ErrorResponse without an error. I shall destroy you")
}
errorMessage := err.Error()
errorStatus := http.StatusInternalServerError
if errors.Is(err, ErrorBadRequest) {
errorStatus = http.StatusBadRequest
}
if errors.Is(err, ErrorMethodNotAllowed) {
errorStatus = http.StatusMethodNotAllowed
}
2020-06-14 18:40:55 +08:00
if errors.Is(err, ErrorNotFound) {
errorStatus = http.StatusNotFound
}
2020-05-31 02:22:25 +08:00
var minioErrorResponse minio.ErrorResponse
if errors.As(err, &minioErrorResponse) {
if minioErrorResponse.Code == "NoSuchKey" {
errorStatus = http.StatusNotFound
}
if minioErrorResponse.Code == "NoSuchBucket" {
errorStatus = http.StatusNotFound
}
2020-06-14 18:40:55 +08:00
// Do not handle MinIO AccessDenied: that's a server error. Our credentials should always be correct
2020-05-31 02:22:25 +08:00
}
// Let Header.Write() handle escaping
w.Header().Add("X-Debug-Error", errorMessage)
w.WriteHeader(errorStatus)
}
2020-06-14 18:40:55 +08:00
func ErrorFromStatus(code int) error {
if code == http.StatusOK {
return nil
}
2020-08-23 00:21:56 +08:00
if code == http.StatusNotFound {
return ErrorNotFound
}
if code == http.StatusBadRequest {
return ErrorBadRequest
}
if code == http.StatusUnauthorized {
return ErrorUnauthorized
}
2020-06-14 18:40:55 +08:00
return fmt.Errorf("%s", http.StatusText(code))
}