errors.go 994 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package main
  2. import (
  3. "fmt"
  4. "runtime"
  5. "strings"
  6. )
  7. type imgproxyError struct {
  8. StatusCode int
  9. Message string
  10. PublicMessage string
  11. }
  12. func (e imgproxyError) Error() string {
  13. return e.Message
  14. }
  15. func newError(status int, msg string, pub string) imgproxyError {
  16. return imgproxyError{status, msg, pub}
  17. }
  18. func newUnexpectedError(err error, skip int) imgproxyError {
  19. msg := fmt.Sprintf("Unexpected error: %s\n%s", err, stacktrace(skip+1))
  20. return imgproxyError{500, msg, "Internal error"}
  21. }
  22. var (
  23. invalidSecretErr = newError(403, "Invalid secret", "Forbidden")
  24. invalidMethodErr = newError(422, "Invalid request method", "Method doesn't allowed")
  25. )
  26. func stacktrace(skip int) string {
  27. callers := make([]uintptr, 10)
  28. n := runtime.Callers(skip+1, callers)
  29. lines := make([]string, n)
  30. for i, pc := range callers[:n] {
  31. f := runtime.FuncForPC(pc)
  32. file, line := f.FileLine(pc)
  33. lines[i] = fmt.Sprintf("%s:%d %s", file, line, f.Name())
  34. }
  35. return strings.Join(lines, "\n")
  36. }