How to short-circuit HTMLRewriter

I am looking for a way to short-circuit the behavior of HTMLRewriter.

That is to say, as soon as the contents of my response matches a certain criteria, I’d like to respond immediately with a different response.

The only documented way I have seen to “short-circuit” the HTMLRewriter is by throwing an error, but that seems pretty nasty to use exceptions for this type of thing.


async function handle(request) {
  let oldResponse = await fetch(request)
  let newResponse = new HTMLRewriter()
    .on("*", {
      text(text) {
        return new Response("Ninja not found", { status: 404 })

  return newResponse

The above does not work, but I hope my intent is clear. Is there a way I could achieve something like this where the response is discarded and replaced with a different one under certain conditions in HTMLRewriter?

class ImageHandler {
  element(element) {
    this.foundImage = element.getAttribute('src')

async function handleRequest(request) {
  const resp = await fetch(url)
  const handler = new ImageHandler()
  const body = await new HTMLRewriter()
    .on('img#image-item', handler)

  if (handler.foundImage) {
    return fetch(handler.foundImage)
  } else {
    return new Response(body, resp)

more example Document parsing and returning content (scraping) using the HTMLRewriter · Issue #658 · cloudflare/workers-docs · GitHub