Errors
Errors on images
Modifiers return the image instead of an error, so calls chain. When a modifier fails, such as Blur(500) or Trim on an animation, the image keeps the error and every later modifier does nothing. Only the first error is kept.
Err returns that error. Encode, Save, Store, and image.Response return it too, so you usually check once, at the end:
encoded, err := img.Scale(800, 0).Sharpen(10).Encode(image.WEBP)
if err != nil {
return err
}Error messages follow Laravel for Go's style. They say what happened and how to fix it:
image: the blur level 500 is outside 0 to 100: pass a value in that rangeSentinel errors
Errors about the image data and formats wrap two sentinel errors, which you may test with errors.Is:
| Error | Meaning | Status from web.Fail |
|---|---|---|
image.ErrDecoder | The data isn't an image the package can decode. | 422 Unprocessable Entity |
image.ErrNotSupported | The format or operation isn't supported, such as AVIF or trimming an animation. | 415 Unsupported Media Type |
Open returns an error that matches fs.ErrNotExist when the file is missing. Other errors, such as a missing upload, a quality outside 0 to 100, or Save("") for an image that wasn't opened from a file, wrap neither, so web.Fail answers them with 500 Internal Server Error. Validate user input before it reaches the package.
img, err := image.From(r).Upload(form.Avatar)
if errors.Is(err, image.ErrDecoder) {
return web.Fail(err) // 422
}Errors in responses
image.Response renders an encoding error the same way web.Fail does. In a handler, you may return the response without checking Err first:
return image.Response(img.Cover(300, 300, image.Center), image.WEBP)