err.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // handlererr package exposes helper functions for error handling in request handlers
  2. // (like streaming or processing).
  3. package handlererr
  4. import (
  5. "context"
  6. "net/http"
  7. "github.com/imgproxy/imgproxy/v3/ierrors"
  8. "github.com/imgproxy/imgproxy/v3/metrics"
  9. )
  10. // Error types for categorizing errors in the error collector
  11. const (
  12. ErrTypeTimeout = "timeout"
  13. ErrTypeStreaming = "streaming"
  14. ErrTypeDownload = "download"
  15. ErrTypeSvgProcessing = "svg_processing"
  16. ErrTypeProcessing = "processing"
  17. ErrTypePathParsing = "path_parsing"
  18. ErrTypeSecurity = "security"
  19. ErrTypeQueue = "queue"
  20. ErrTypeIO = "IO"
  21. ErrTypeDownloadTimeout = "download"
  22. )
  23. // Send sends an error to the error collector if the error is not a 499 (client closed request)
  24. func Send(ctx context.Context, errType string, err error) {
  25. if ierr, ok := err.(*ierrors.Error); ok {
  26. switch ierr.StatusCode() {
  27. case http.StatusServiceUnavailable:
  28. errType = ErrTypeTimeout
  29. case 499:
  30. return // no need to report request closed by the client
  31. }
  32. }
  33. metrics.SendError(ctx, errType, err)
  34. }
  35. // SendAndPanic sends an error to the error collector and panics with that error.
  36. func SendAndPanic(ctx context.Context, errType string, err error) {
  37. Send(ctx, errType, err)
  38. panic(err)
  39. }
  40. // Check checks if the error is not nil and sends it to the error collector, panicking if it is not nil.
  41. func Check(ctx context.Context, errType string, err error) {
  42. if err == nil {
  43. return
  44. }
  45. SendAndPanic(ctx, errType, err)
  46. }