Como tratar erro 404 de rota ou página não existente no Express

Como tratar erro 404 de rota ou página não existente no Express

How to Handle 404 Errors in Express

Introduction to Error Handling

  • The video introduces the topic of handling non-existent route errors in Express, specifically focusing on the common 400 error.
  • It emphasizes the importance of informing users when they request a page that does not exist, as Express lacks specific handling for 404 errors.

Understanding Route Handling

  • When a user requests a non-existent route, Express attempts to match it against registered routes but fails if none are found.
  • A solution is proposed: adding a catch-all route at the end of all defined routes to handle 404 errors effectively.

Implementing Error Handling

  • The presenter demonstrates how to create an error-handling route that triggers when no other routes match.
  • An example code snippet shows three predefined routes and how an invalid request leads to a custom error response.

Customizing Error Responses

  • After defining the error handler, it responds with a status code of 404 and a message indicating that the requested route does not exist.
  • The presenter highlights that this method allows for consistent error messaging across applications.

Alternative Response Formats

  • Besides returning plain text messages, it's suggested that returning JSON responses can be beneficial for API compatibility.
  • Returning structured data (like JSON objects) is recommended for better integration with front-end frameworks or clients.

Rendering Custom Error Pages

  • The video discusses rendering an HTML page for 404 errors instead of just sending text or JSON responses.
  • Instructions are provided on installing necessary packages (e.g., EJS template engine), which will allow dynamic rendering of views.

Creating and Using Views

  • A new directory named "views" is created where an HTML file (404.ejs) will be stored to display custom error messages.
  • The presenter explains how to set up this view file with basic HTML structure and dynamic content using EJS syntax.

Final Implementation Steps

  • Finally, the server setup includes routing logic that renders the custom 404 page whenever an undefined route is accessed.
  • This ensures users receive clear feedback about their navigation mistakes while maintaining application integrity.

Error Handling in Web Development: Custom 404 Pages

Creating a User-Friendly 404 Error Page

  • The video discusses the implementation of a custom error page for handling 404 errors, emphasizing that systems typically use more visually appealing layouts to enhance user experience.
  • A personalized layout is introduced, showcasing how to replace the default error page with a more engaging design using JavaScript.
  • The presenter highlights features of the new layout, including animations and a clear message indicating that the requested page was not found, along with a button redirecting users back to the homepage.
  • The updated page is described as significantly more attractive and user-friendly, providing visual feedback when an invalid route is accessed while still informing users about missing pages.
  • The source for the custom layout is mentioned as freefromcandy.com, where various templates for 404 error pages can be found. Links to this site and example code will be provided in the video's description.

Conclusion and Engagement

  • Viewers are encouraged to like the video if they found it helpful and are invited to leave comments or questions for further engagement. Additionally, they are prompted to subscribe and activate notifications for future content updates.
Video description

O erro 404 é utilizado quando uma rota, página do sistema não é encontrado. Esse tipo de erro é comum acontecer quando o usuário solicita uma rota da API que não existe, ou tenta entrar em uma página que não existe mais. O Express tem uma forma de tratar esse erro para informar ao usuário de maneira mais amigável que ele aconteceu, seja via API, caso seu backend seja uma API rest, ou criando uma página para isso. Código fonte do vídeo: https://codesandbox.io/s/404-cyp2w?file=/src/index.js Site FreeFrontend: https://freefrontend.com/html-css-404-page-templates/ Artigo relacionado ao assunto: https://programandosolucoes.dev.br/2021/03/16/erro-404-express/ Tempos do vídeo 00:00 - Apresentação 00:28 - Introdução 02:30 - Midleware erro 404 04:06 - Retornar json 04:56 - Renderizando página de erro 07:52 - Personalizando página de erro --- Mais artigos relacionados a VueJS, NodeJS, Javascript e programação nos blogs: https://www.cupcom.com.br/ https://programandosolucoes.dev.br/ Siga o Instagram @programandosolucoes lá eu sempre posto dicas curtas sobre Javascript, Node, VueJS e muito mais Link direto para o Instagram: https://www.instagram.com/programandosolucoes/ Para uma leitura sobre este conteúdo, acesse https://programandosolucoes.dev.br/ Receba a novos artigos e vídeos: https://programandosolucoes.dev.br/assinar-a-newsletter/