Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

290
Views
¿Está bien mezclar .catch() con async/await para el manejo de errores?

Normalmente, cuando se trata del manejo de errores para async / awai t en JavaScript, la gente usa por defecto try / catch . Pero me pregunto si puedo usar .catch() en su lugar, como en

 const res = await fetch().catch((error) => ( // error handling )); const json = await res.json();

Me pregunto si esto funciona igual que un bloque try / catch

 try { const res = await fetch() const json = await res.json(); } catch(e) { // error handling }

Entiendo que, técnicamente, el bloque try / catch puede detectar errores generados por res.json(); también, así que supongo que todavía es preferible al ejemplo .catch() .

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Me pregunto si esto funciona igual que el bloque try / catch

No, como ya te has respondido a ti mismo. En particular, el bloque de try alrededor res.json() también detectaría errores arrojados por eso, que puede o no desear .

Además, si no está volviendo a throw una excepción desde su devolución de llamada .catch() , su valor de retorno se convertirá en el valor res y se seguirá llamando a res.json() , por lo que es mejor que return una instancia de Response válida.

¿Está bien mezclar .catch() con async / await para el manejo de errores?

¡Si, absolutamente! Es una herramienta mucho más versátil si desea manejar errores de una promesa específica solamente. Hacer eso con try / catch es mucho más feo , por lo que incluso recomendaría usar .catch() para volver a generar errores (cuando desea un mejor mensaje de error):

 const res = await fetch(…).catch(error => { throw new Error('Could not reach backend', {cause: error}); }); if (!res.ok) throw new Error(`Backend responded with ${res.status} error: ${await res.text()}`); const data = await res.json();

Si no desea volver a throw , le recomiendo usar .then() para manejar las rutas de éxito y falla por separado :

 const data = await fetch(…).then(res => { if (!res.ok) { console.error(`Backend responded with ${res.status} error`); return null; } return res.json(); }, error => { console.error('Could not reach backend', error); return null; });
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!