Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

117
Vistas
catching exception thrown by service worker message event

I can't catch an exception thrown by the service worker's message event..

The client uses following code to execute the command on the SW:

  import { messageSW } from "workbox-window";

  // .. code for Workbox initialization/registration omitted

  messageSW(registration?.active, { type: "SYNC" })
    .then((results) => {
      console.log("done");
    })
    .catch((e) => {
      console.error(e);
    });

On the SW (sw.js) side I have the following code:

self.addEventListener("message", async (event) => {
  if (requestType === "SYNC") {
    event.ports[0].postMessage(await longRunningTask());
  }
});

This solution works OK as long as the SW is not throwing any exceptions. Meaning that the client prints the "done" message after the long running process on the SW is executed. If the exception is thrown nothing gets returned, ever.

I have managed to fix the problem by doing the following:

self.addEventListener("message", async (event) => {
  if (requestType === "SYNC") {
    try {
      event.ports[0].postMessage(await longRunningTask());
    } catch (error) {
      event.ports[0].postMessage(error);
    }
  }
});

In this case - the result is always returned regardless, "done" is printed, but:

  1. how do I actually produce an exception from the service worker, so the client could catch and handle it?
  2. In general it would be good to hear if what I am doing is an appropriate approach to how asynchronous code on the SW shall be invoked from the client...
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Here is my own solution I ended up using:

on service worker side - helper method:

async function replyToSenderAsync(event, task) {
  let isCanReply = event.ports && event.ports.length >= 0;
  try {
    const result = await task();
    if (isCanReply) {
      event.ports[0].postMessage({ error: null, message: result });
    }
  } catch (error) {
    if (isCanReply) {
      event.ports[0].postMessage({ error: error, message: null });
    }
  }
}

When exception is caught we set the error property. Use as:

self.addEventListener("message", async (event) => {
  const requestType = event?.data?.type;
  if (requestType === "QUEUE_CLEAR") {
    await replyToSenderAsync(event, async () => await clearQueueAsync());
  }
});

on client side request wrapper:

function sendMessageToSWAsync(targetSW, messageType, message) {
  return new Promise(function (resolve, reject) {
    if (
      !isServiceWorkerSupported.value ||
      !isServiceWorkerRegistered.value ||
      !targetSW
    ) {
      reject(new Error("Unable to send the message to a service worker"));
    }

    try {
      messageSW(targetSW, { type: messageType, message: message })
        .then((messageResponse) => {
          if (!messageResponse) {
            reject(new Error("Service worker responsed with empty response"));
          } else {
            if (messageResponse.error) {
              reject(messageResponse.error);
            } else {
              resolve(messageResponse.message);
            }
          }
        })
        .catch((messageError) => {
          reject(messageError);
        });
    } catch (error) {
      reject(error);
    }
  });
}

The magic here is to read the error property and reject the promise if that is the case. (hence causing an exception to be thrown. Use as

try {
    let response = await sendMessageToSWAsync(registration?.active, "QUEUE_GET_ALL");
}
catch(error) {

}

sendMessageToSWAsync(registration?.active, "QUEUE_GET_ALL")
    .then((response) => {})
    .catch((error) => {})
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda