{"id":669,"date":"2024-07-30T19:55:06","date_gmt":"2024-07-30T17:55:06","guid":{"rendered":"https:\/\/blog.sutilweb.eu\/?page_id=669"},"modified":"2024-07-30T19:55:07","modified_gmt":"2024-07-30T17:55:07","slug":"004-manejo-de-errores-en-javascript","status":"publish","type":"page","link":"https:\/\/sutilweb.eu\/index.php\/lenguajes\/javascript\/javascript-practico\/04-estructuras-de-control-en-javascript\/004-manejo-de-errores-en-javascript\/","title":{"rendered":"004. Manejo de errores en Javascript"},"content":{"rendered":"\n<p>En este cap\u00edtulo vamos a ver el <strong>manejo de errores<\/strong> en <strong>Javascript<\/strong>. Para el <strong>manejo de errores<\/strong>, <strong>Javascript<\/strong> tiene un mecanismo parecido a un <strong><em>if else<\/em><\/strong>, es denominado <strong><em>try catch finally<\/em><\/strong>. Es una estructura que nos permite evaluar ciertos fragmentos de c\u00f3digo y cuando haya alg\u00fan mensaje de error, o m\u00e1s bien, cuando nuestro c\u00f3digo genere alg\u00fan lanzamiento de error, entonces se captura en la parte del <strong><em>catch<\/em><\/strong>, y de esta manera es una forma de ir gestionando el manejo de errores.<\/p>\n\n\n\n<!--more-->\n\n\n\n<p>La sintaxis es la siguiente.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&nbsp; &nbsp; &nbsp; &nbsp; try {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(\"En el try se agrega el c\u00f3digo a evaluar\")\n&nbsp; &nbsp; &nbsp; &nbsp; } catch (error) {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(\"Catch captura cualquier error surgido o lanzado en el try\")\n&nbsp; &nbsp; &nbsp; &nbsp; } finally {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(\"El bloque finally se ejecutar\u00e1 siempre al final de un bloque try catch\")\n&nbsp; &nbsp; &nbsp; &nbsp; }<\/pre>\n\n\n\n<p>Si en el c\u00f3digo del <strong><em>try<\/em> <\/strong>se ejecuta alg\u00fan error, quien va a capturar ese error va a ser la parte del <strong><em>catch<\/em><\/strong>. Finalmente <strong><em>finally<\/em> <\/strong>se ejecutar\u00e1 siempre al final de un bloque <strong><em>try catch<\/em><\/strong>.<\/p>\n\n\n\n<p>Vamos a hacer un segundo ejm en el cual creamos una variable que no se ha declarado para que d\u00e9 un error aposta en el <strong><em>try<\/em><\/strong>.<\/p>\n\n\n\n<p><strong>Ejm<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&nbsp; &nbsp; &nbsp; &nbsp; try {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; noExiste;\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(\"Mensaje que aparece si todo va bien\");\n&nbsp; &nbsp; &nbsp; &nbsp; } catch (error) {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(\"Esto aparecer\u00e1 si d\u00e1 error\");\n&nbsp; &nbsp; &nbsp; &nbsp; } finally {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(\"S\u00ed o s\u00ed esto aparecer\u00e1 siempre\");\n&nbsp; &nbsp; &nbsp; &nbsp; }<\/pre>\n\n\n\n<p>Lo interesante es mandar a la consola imprimir ese error para ver como se presenta, le a\u00f1adimos una l\u00ednea a nuestro <strong><em>catch<\/em><\/strong>.<\/p>\n\n\n\n<p><strong>Ejm<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&nbsp; &nbsp; &nbsp; &nbsp; try {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; noExiste;\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(\"Mensaje que aparece si todo va bien\");\n&nbsp; &nbsp; &nbsp; &nbsp; } catch (error) {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(\"Esto aparecer\u00e1 si d\u00e1 error\");\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(error);\n&nbsp; &nbsp; &nbsp; &nbsp; } finally {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(\"S\u00ed o s\u00ed esto aparecer\u00e1 siempre\");\n&nbsp; &nbsp; &nbsp; &nbsp; }<\/pre>\n\n\n\n<p>A veces podemos tener la necesidad, a lo mejor de lanzar un error aposta, por ejm, estamos pidiendo informaci\u00f3n de un formulario, y entonces forzosamente necesitamos que cierta informaci\u00f3n llegue como datos num\u00e9ricos, y llegan como texto, entonces podr\u00edamos lanzar un error personalizado que dijese que esper\u00e1bamos n\u00fameros y est\u00e1n enviando letras. Por lo tanto se utiliza para arrojar errores que est\u00e9n dentro de la l\u00f3gica de nuestro programa, no necesariamente un error de sintaxis. Eso es lo que hacen mucho por ejm los <strong>desarrolladores de APIs<\/strong>, cuando no cumplimos con mandar la informaci\u00f3n correcta hacia una <strong>API<\/strong> para ejecutar cierto proceso, va a mandar un mensaje de error de por qu\u00e9 no se est\u00e1 ejecutando. En ese sentido un <strong><em>try catch<\/em><\/strong> nos puede servir.<\/p>\n\n\n\n<p>En el momento de que el <strong><em>try catch<\/em><\/strong> detecta el error, imprimir\u00eda lo anterior, pero lo posterior al error ya no lo imprime, es decir, detiene la ejecuci\u00f3n del <strong><em>try<\/em> <\/strong>en el momento en que detecta el error, y lanza la ejecuci\u00f3n del <strong><em>catch<\/em><\/strong>, es como si fuera un <strong><em>return<\/em><\/strong>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Personalizar nuestros propios mensajes<\/h2>\n\n\n\n<p>Ve\u00e1moslo con un ejm.<\/p>\n\n\n\n<p><strong>Ejm<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&nbsp; &nbsp; &nbsp; &nbsp; try {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let numero = \"y\";\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(isNaN(numero)) {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new Error(\"El caracter introducido no es un n\u00famero\");\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }\n\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(numero * numero);\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\n&nbsp; &nbsp; &nbsp; &nbsp; } catch (error) {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(\"Se produjo el siguiente error. \" + error);\n&nbsp; &nbsp; &nbsp; &nbsp; }<\/pre>\n\n\n\n<p>Como vemos, estamos enviando un mensaje de error totalmente personalizado. Como podemos observar, con este tipo de <strong>estructura de control<\/strong> podemos trabajar de una manera m\u00e1s ordenada e incluso mejor evaluada, ya que estamos pensando en donde podemos tener ciertos errores (no necesariamente de sintaxis).<\/p>\n","protected":false},"excerpt":{"rendered":"<p>En este cap\u00edtulo vamos a ver el manejo de errores en Javascript. Para el manejo de errores, Javascript tiene un [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":658,"menu_order":3,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_uag_custom_page_level_css":"","site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"class_list":["post-669","page","type-page","status-publish","hentry"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false},"uagb_author_info":{"display_name":"Sutil Web","author_link":"https:\/\/sutilweb.eu\/index.php\/author\/sutilweb\/"},"uagb_comment_info":0,"uagb_excerpt":"En este cap\u00edtulo vamos a ver el manejo de errores en Javascript. Para el manejo de errores, Javascript tiene un [&hellip;]","_links":{"self":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/669","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/comments?post=669"}],"version-history":[{"count":1,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/669\/revisions"}],"predecessor-version":[{"id":670,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/669\/revisions\/670"}],"up":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/658"}],"wp:attachment":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/media?parent=669"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}