Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

342
Visualizações
how to propagate uncaught errors in promise contexts to window.onerror?

unlike what one may expect, the following code will not trigger the window.error handler

window.addEventListener("error",function(error){
    alert("uncaught error somewhere!");
});

(async function(){
let foo= ((await ( await fetch("/no_json_plz_i_want_an_error")).json()));
})();

(reason being "because the error occurs in a promise context" according to a comment on this question: why doesn't fetch().json() errors trigger window.onerror? )

what is the correct way to explicitly propagate it to the window error handler? this doesn't work either, for some reason it still doesn't propagate to window.error:

(async function(){
let foo= ((await ( await fetch("/no_json_plz_i_want_an_error")).json()));
})().catch(function(err){
    throw err;
});

this doesn't seem to work either (why? no idea)

(async function(){
let foo= ((await ( await fetch("/no_json_plz_i_want_an_error")).json()));
})().catch(function(err){
    let ev = new ErrorEvent(err.message, err);
    window.dispatchEvent(ev);
});

and this approach fails with the error Uncaught (in promise) DOMException: Failed to execute 'dispatchEvent' on 'EventTarget': The event provided is uninitialized., whatever that means

(async function(){
let foo= ((await ( await fetch("/no_json_plz_i_want_an_error")).json()));
})().catch(function(err){
  let ev= document.createEvent("ErrorEvent");
  ev.error=err;
  window.dispatchEvent(ev);
});

so.. what is the correct way to do it?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use unhandledrejection event to catch the promises error in window object instead.

Edit:

As fetch() will still return response object and there is no error throwing. You can throw a error when the response.ok is false. See function run1 below:

The run2 function will throw a JSON token error as the response.ok is false and it tries to parse the data.

You may try to run in your local environment because fiddle may wrap the error handling in the console.

window.addEventListener("unhandledrejection", function (e) {
  console.log("Error occurred: " + e.reason.message);
});

(async function run1() {
  try {
    let response = await fetch("/no_json_plz_i_want_an_error");
    if (response.ok) {
      const data = response.json();
    } else {
      throw new Error("Unable to fetch()");
    }
  } catch (err) {
    throw new Error(err);
  }
})();

(async function run2() {
  try {
    await (await fetch("/no_json_plz_i_want_an_error")).json();
  } catch (err) {
    throw new Error(err);
  }
})();

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda