Skip to content

Add throws() to OptimizerChain for optimizer failure handling - #241

Merged
freekmurze merged 2 commits into
spatie:mainfrom
mathiasgrimm:feature/error-handler
Jun 25, 2026
Merged

freekmurze merged 2 commits into
spatie:mainfrom
mathiasgrimm:feature/error-handler

Conversation

@mathiasgrimm

@mathiasgrimm mathiasgrimm commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

Add throws() to OptimizerChain for optimizer failure handling

Problem

When an optimizer fails (for example its binary exits with a non-zero status), OptimizerChain logs the failure and silently continues with the next optimizer. Callers have no way to observe a failure, skip the rest of the chain, or abort the whole optimization. Some failures (such as a Symfony ProcessTimedOutException when an optimizer exceeds its timeout) were also thrown straight out of optimize() with no way to intercept them.

Solution

A single fluent throws() method on OptimizerChain that lets you decide what happens on failure:

// rethrow the failure and abort the chain
$optimizerChain->throws()->optimize($pathToImage);

// keep the default: log and continue
$optimizerChain->throws(false)->optimize($pathToImage);

// decide for yourself
$optimizerChain
    ->throws(function (Throwable $exception, Optimizer $optimizer, Image $image) {
        report($exception);
        // return to continue with the next optimizer, or throw to abort
    })
    ->optimize($pathToImage);
  • throws() / throws(true): rethrow and abort the chain.
  • throws(false): keep the existing log-and-continue behaviour.
  • throws($callable): custom handler receiving the exception, the optimizer and the image. Return to continue, throw to abort.

Internally, a non-zero process exit now raises a ProcessFailedException that flows through the same handler, and any exception raised while applying an optimizer (including former timeouts) is routed through it too.

Bonus fix

An optimizer's temporary file is now cleaned up even when applying it fails. The cleanup runs in a finally block, so a thrown exception (for example a ProcessTimedOutException) no longer leaves the temp file behind. Previously the unlink happened after the process ran, so any exception skipped it and leaked the file.

Backwards compatibility

Fully backwards compatible:

  • If throws() is never called, behaviour is unchanged: failures are logged and the chain continues.
  • Logging is untouched. A dedicated test asserts the emitted log lines are byte-for-byte identical across the pre-PR default, throws(false), throws(true), and both continuing and aborting callbacks. The only difference between modes is whether the chain continues or the exception bubbles.
  • logResult() is kept intact (no removed protected method, so no break for subclasses).
  • No changes to the Optimizer interface or any existing optimizer.
  • The pre-loop Cannot copy file error still bubbles up regardless of this setting, since it happens before any optimizer runs.

Notes

  • throws() accepts bool|callable. Since the package supports PHP 7.3+, where union type hints are unavailable, the argument is validated at runtime and throws an InvalidArgumentException for anything else.

Tests

Adds tests/OptimizerChainErrorHandlerTest.php covering: default-continue, throws() abort, throws(false), continuing and aborting callbacks, the InvalidArgumentException guard, log-line parity across all modes, and that a ProcessFailedException carrying the failed process reaches the handler. Full suite: 32 passing.

Optimizer failures (e.g. a binary exiting non-zero) were always logged
and swallowed, so callers could not observe a failure, skip the rest of
the chain, or abort.

Add a fluent `throws()` control on OptimizerChain:
- `throws()` / `throws(true)` rethrows the failure and aborts the chain
- `throws(false)` keeps the default "log and continue" behaviour
- `throws($callable)` runs a custom handler receiving
  (Throwable $exception, Optimizer $optimizer, Image $image); return to
  continue, throw to abort

Non-zero process exits now raise a ProcessFailedException internally that
flows through the same handler. logResult() is kept intact so existing
log output and the protected extension point are unchanged. With
`throws()` never called the behaviour is identical to before (log and
continue), so this is backwards compatible.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@mathiasgrimm
mathiasgrimm marked this pull request as ready for review June 25, 2026 18:10

@freekmurze freekmurze left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the thorough PR and tests.

The P7.3 CI jobs fail with a ParseError because tests/OptimizerChainErrorHandlerTest.php uses arrow functions (fn () => ..., e.g. lines 110, 124, 134, and $logsFor(fn () => null)). Arrow functions require PHP 7.4+, but the package still supports PHP 7.3 ("php": "^7.3|^8.0"). Could you replace those with regular function () { ... } closures so the 7.3 builds pass?

One thing to confirm: with the default handler, a ProcessTimedOutException that previously bubbled out of optimize() is now caught and swallowed. The description notes this is intentional, just want to make sure that's the desired default rather than only changing behaviour once throws() is opted into.

@freekmurze
freekmurze merged commit 6ad4d36 into spatie:main Jun 25, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants