errors.go 1.1 KB

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