<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Chidiebere</title>
    <description>The latest articles on DEV Community by Chidiebere (@code_black).</description>
    <link>https://dev.to/code_black</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F228708%2F15f3d55c-cc3b-42ef-b662-83d41a63b5d3.jpeg</url>
      <title>DEV Community: Chidiebere</title>
      <link>https://dev.to/code_black</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/code_black"/>
    <language>en</language>
    <item>
      <title>Express.js Server Error Handling Explained</title>
      <dc:creator>Chidiebere</dc:creator>
      <pubDate>Fri, 26 May 2023 14:23:05 +0000</pubDate>
      <link>https://dev.to/code_black/expressjs-server-error-handling-explained-2e4d</link>
      <guid>https://dev.to/code_black/expressjs-server-error-handling-explained-2e4d</guid>
      <description>&lt;p&gt;Effective error handling on the web server is a critical component of developing a resilient system, since when an error is handled effectively, you are less likely to become irritated when anything goes wrong. By supplying helpful information and precise error code, you will be able to troubleshoot quickly.&lt;br&gt;
Only operational errors will be addressed in this article. Before we go into how to handle operational failures, let's build a node.js server using express.js. Express.js is built on top of node.js, a powerful JavaScript engine that enables server-side programming.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Table Of Contents&lt;/strong&gt;&lt;br&gt;
        Setting up Express Server&lt;br&gt;
        Building Components for Efficiently Dealing With Errors&lt;br&gt;
        Endpoint Creation&lt;br&gt;
        Web Server Example Errors&lt;/p&gt;

&lt;p&gt;Let's dive in 🦅.&lt;/p&gt;
&lt;h2&gt;
  
  
  Setting up Express Server &lt;a&gt;&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Creating the project&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir error-handling
cd error-handling
npm init
npm i express nodemon
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Use mkdir to create a folder in the root directory and move &lt;code&gt;(cd)&lt;/code&gt; to the folder that was created.&lt;/li&gt;
&lt;li&gt;Create a &lt;code&gt;package.json&lt;/code&gt; that will keep record of all the dependencies that will be used for this article.&lt;/li&gt;
&lt;li&gt;Install the following dependencies.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;nodemon&lt;/code&gt; to listen for changes in the source file and restart the server&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Running the server&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;create an &lt;code&gt;app.js&lt;/code&gt; file
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(app.js)
const app = express();
const PORT = 3000;

app.get('/', (req, res) =&amp;gt; {
  res.send('Welcome to error handling in Express :)');
});

app.listen(PORT, () =&amp;gt; {
  console.log(`Server is running on port ${PORT}`)
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;In &lt;code&gt;app.js&lt;/code&gt; create an instance of express&lt;/li&gt;
&lt;li&gt;Create the server and listen to incoming HTTP request on port 3000.&lt;/li&gt;
&lt;li&gt;Define the root route that handles HTTP &lt;code&gt;GET&lt;/code&gt; request
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "name": "error-handling",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "nodemon app.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2",
    "joi": "^17.9.2",
    "nodemon": "^2.0.22"
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Add a start script in the &lt;code&gt;package.json&lt;/code&gt; file, the start script will start the server using &lt;code&gt;nodemon&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;On postman run &lt;code&gt;localhost:3000/&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm2mdcqcqfcxxtcc8hnc6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm2mdcqcqfcxxtcc8hnc6.png" alt="server post-man" width="800" height="102"&gt;&lt;/a&gt;&lt;br&gt;
Hurray we have our server running 🎉 &lt;/p&gt;


&lt;h2&gt;
  
  
  Building Components for Efficiently Dealing With Errors &lt;a&gt;&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Error handler middleware:&lt;/strong&gt; Any code that runs between the request and the answer is referred to as middleware. The error handler middleware in this scenario will be an abstraction of the many errors that will be handled in the server.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It accepts error, request, response and next parameters.&lt;/li&gt;
&lt;li&gt;If the error that is passed is an instance of the custom AppError, &lt;code&gt;handleError&lt;/code&gt; function respond with the statusCode, errorMessage and errorStatus.&lt;/li&gt;
&lt;li&gt;If the error is not an instance of AppError the respond will be a 500 errorCode and an internal server error message, because the error that occurred wasn't taken into consideration.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(middleware/handlError.js)

const AppError = require('../utils/AppError');

const handleError = (err, req, res, next) =&amp;gt; {

  if (err instanceof AppError) {
    return res.status(err.statusCode).json({ 
      message: err.message, 
      status: err.status 
    });
  }

  res.status(500).json({ 
    message: 'Internal Server Error', 
    status: 500 
  });
}

module.exports = handleError;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;strong&gt;AppError Class:&lt;/strong&gt; A customized error called AppError extends the &lt;code&gt;new Error(..)&lt;/code&gt; base error class.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It accepts the &lt;code&gt;message&lt;/code&gt; argument and the &lt;code&gt;errorCode&lt;/code&gt;. &lt;/li&gt;
&lt;li&gt;Super method runs the base error constructor with the message parameter.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(utils/AppError.js)

class AppError extends Error {
  constructor(statusCode, message) {
    super(message);

    this.statusCode = statusCode;
    this.status = `${statusCode}`.startsWith("4") ? "fail" : "error";
  }
}

module.exports = AppError;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;strong&gt;TryCatch Abstraction:&lt;/strong&gt; An abstraction called tryCatch delivers a middleware with a try-and-catch block when it receives a controller as an argument. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The controller is called in the &lt;code&gt;try&lt;/code&gt; block, and If an error occurs the &lt;code&gt;next&lt;/code&gt; parameter is called in the &lt;code&gt;catch&lt;/code&gt; block with the specified error.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;exports.tryCatch = (controller) =&amp;gt; async (req, res, next) =&amp;gt; {
  try {
    await controller(req, res, next);
  } catch(err) {
    next(err);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Endpoint Creation &lt;a&gt;&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;Before we build a model endpoint that will be utilized to show how errors are effectively handled. Let's add &lt;code&gt;handleError&lt;/code&gt; middleware to the server's index file &lt;code&gt;(app.js)&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express');
const handleError = require('./middleware/handleError');

const app = express();
const PORT = 3000;

app.get('/', (req, res) =&amp;gt; {
  res.send('Welcome to error handling in Express :)');
});

// error handler middleware
app.use(handleError);

app.listen(PORT, () =&amp;gt; {
  console.log(`Server is running on port ${PORT}`)
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;handleError&lt;/code&gt; middleware will be used to handle errors that occurs during a HTTP process.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Creating an Example Express Router&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;create a user endpoint that returns an array of users. This endpoint will be used to experiment several operational error that can be handled in a HTTP process.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(routes/user.route.js)

const express = require('express');
const { tryCatch } = require('../utils/tryCatch');
const { getUsers } = require('../service/users.service');

const router = express.Router();

const userController = tryCatch(async (req, res, next) =&amp;gt; {
  const users = await getUsers();
  res.status(200).json(users);
});

router.get('/user', userController);

module.exports = router;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Web Server Example Errors &lt;a&gt;&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Bad Request Error, often known as 400:&lt;/strong&gt; When the web server cannot handle the request given by the web client, a 400 error is one form of HTTP response status that appears. This kind of error is likely caused by the web client. There are several things that might result in a 400 error.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;When the endpoint URL contains a mistake&lt;/li&gt;
&lt;li&gt;When the web client gives the web server inaccurate or incomplete information.&lt;/li&gt;
&lt;li&gt;A browser or internet connection issue for the user&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;code example&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;We can handle an invalid endpoint error in the &lt;code&gt;app.js&lt;/code&gt; file, which is an example of a bad request error.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(app.js)
app.get('*', (req, res) =&amp;gt; {
  throw new AppError(400, 'Invalid endpoint');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The asterisk character in Express Router can be used to match any number of characters in a route. The asterisk route, for example, will be triggered when the specified URL does not match any of the existing routes. In that instance, the web server returns a 400 error code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Unauthorized Error, often known as 401:&lt;/strong&gt; When a web client communicates with a web server without the necessary rights, the web server responds with a 401 error, indicating that the user is not authorized to do the intended activity.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;code example&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;To demonstrate the 401 error, let's build a user authentication middleware that checks to see if the user is authorized before completing the user request.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const AppError = require('../utils/AppError');

const authenticated = (req, res, next) =&amp;gt; {
  const isAuthenticated = req.headers.authorization;

  if (!isAuthenticated) {
    throw new AppError(401, 'unauthorized request');
  }

  next();
}

module.exports = authenticated;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The authorized middleware will then be used in the user route.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(routes/user.route.js)

router.get('/user', authenticated, userController);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you query the &lt;code&gt;/user&lt;/code&gt; endpoint in Postman without authorization, you will receive a 401 error, as seen in the picture below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcyxb0zr257lzawp6zbh4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcyxb0zr257lzawp6zbh4.png" alt="post-man" width="800" height="107"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Not Found Error, often known as 404:&lt;/strong&gt; A 404 HTTP response status occurs when the web client can interact with the web server but the web server is unable to locate the requested resource. Consider the following scenario: you attempt to fetch your t-shirt from your closet and you can't find it, but you can go into your closet. I hope this was helpful XD.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;code example&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Assume there are no users on the server at the moment. When we request the users, the server returns a 404 error. The modifications may be done on the user controller.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const userController = tryCatch(async (req, res, next) =&amp;gt; {
  const users = undefined;
  if (!users) {
    throw new AppError(404, 'No users found')
  }
  res.status(200).json(users);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run the &lt;code&gt;/user&lt;/code&gt; endpoint in your postman.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Internal Server error, often known as 500:&lt;/strong&gt; A 500 response status indicates a web server issue and has nothing to do with the web client. The following factors may contribute to the occurrence of a 500 error:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;When a problem arises with the web server hosting provider&lt;/li&gt;
&lt;li&gt;The reason for a failed database connection&lt;/li&gt;
&lt;li&gt;A programming error occurred in the web server code.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Finally, it is critical to always have a correct error-handling structure on your web server in order to maximize the possibilities of troubleshooting specific operational errors that may occur when working on the web server. I recommend you read &lt;a href="http://expressjs.com/en/guide/error-handling.html#error-handling" rel="noopener noreferrer"&gt;this&lt;/a&gt; to learn more about how to handle errors efficiently in an express server.&lt;br&gt;
Remember that your education does not end here. Thank you for sticking with me to the finish.&lt;/p&gt;




&lt;h2&gt;
  
  
  Resources
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="http://expressjs.com/en/guide/error-handling.html#error-handling" rel="noopener noreferrer"&gt;Express.js Documentation&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://github.com/daveOnactive/error-handling" rel="noopener noreferrer"&gt;Github Repo&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>express</category>
      <category>javascript</category>
      <category>beginners</category>
      <category>node</category>
    </item>
  </channel>
</rss>
