error.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package grab
  2. import (
  3. "fmt"
  4. )
  5. // error codes
  6. const (
  7. errBadLength = iota
  8. errNoFilename
  9. errChecksumMismatch
  10. errBadDestination
  11. )
  12. // grabError is a custom error type
  13. type grabError struct {
  14. err string
  15. code int
  16. }
  17. // Error returns the error string of a grabError.
  18. func (c *grabError) Error() string {
  19. return c.err
  20. }
  21. // newGrabError creates a new grabError instance with the given code and
  22. // message.
  23. func newGrabError(code int, format string, a ...interface{}) error {
  24. return &grabError{
  25. err: fmt.Sprintf(format, a...),
  26. code: code,
  27. }
  28. }
  29. // isErrorType returns true if the given error is a grabError with the specified
  30. // error code.
  31. func isErrorType(err error, code int) bool {
  32. if gerr, ok := err.(*grabError); ok {
  33. return gerr.code == code
  34. }
  35. return false
  36. }
  37. // IsContentLengthMismatch returns a boolean indicating whether the error is
  38. // known to report that a HTTP response indicated that the requested file is not
  39. // the expected length.
  40. func IsContentLengthMismatch(err error) bool {
  41. return isErrorType(err, errBadLength)
  42. }
  43. // IsNoFilename returns a boolean indicating whether the error is known to
  44. // report that a destination filename could not be determined from the
  45. // Content-Disposition headers of a HTTP response or the requested URL path.
  46. func IsNoFilename(err error) bool {
  47. return isErrorType(err, errNoFilename)
  48. }
  49. // IsChecksumMismatch returns a boolean indicating whether the error is known to
  50. // report that the downloaded file did not match the expected checksum value.
  51. func IsChecksumMismatch(err error) bool {
  52. return isErrorType(err, errChecksumMismatch)
  53. }
  54. // IsBadDestination returns a boolean indicating whether the error is known to
  55. // report that the given destination path is not valid for the requested
  56. // operation.
  57. func IsBadDestination(err error) bool {
  58. return isErrorType(err, errBadDestination)
  59. }