Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Recruitment

    Enhancing Recruitment: The Crucial Role of Diversity and Inclusion

    Entrepreneurship

    8 Best Blogs for Entrepreneurs: Start Business, Grow Professionally, or Change Your Life

    Events

    Full List of JavaScript Conferences 2020 [41 Events] Updated 28.08.2020

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Wednesday, September 10
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / JavaScript / Node.js / Node.js Lessons / Node.js Lesson 8: Inheritance from Errors, Error
    JavaScript

    Node.js Lesson 8: Inheritance from Errors, Error

    Mohammad Shad MirzaBy Mohammad Shad MirzaOctober 28, 2020No Comments6 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Node.js Lesson 8: Inheritance from Errors, Error
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link

    Hello everyone, today we are going to talk about error handling in Nodejs with the help of inheritance. We will see what are general problems that can arise and how to solve. We will also learn how to print the stack trace of an issue to provide a better debugging experience to the developer. Let’s start.

    Let’s understand the problem within the error handling

    Inheritance of a built object from error is different in Nodejs. Let’s look at this code snippet:

    const util = require('util');  
      
    const phrases = {  
      "hello": "Hello",  
      "world": "World"  
    };  
      
    
    function getPhrase(name) {  
      if (!phrases[name]) {  
        throw new Error("There is no such pharase: " + name);  
      }  
      return phrases[name];  
    }  
      
      
    function makePage(url) {  
      if (url != 'index.html') {  
        throw new Error("There is no such page");  
      }  
      
      return util.format("%s, %s!", getPhrase("hello"), getPhrase("world"));  
    }  
      
      
    const page = makePage('index.html');  
    console.log(page);

    Here, we have two functions to emphasize. The first one is getPhrase. It’s a dictionary-like function that takes a key and finds its value. If the key passed is not associated with any value then we simply throw an error that the requested phrase is not available.

    In the second function makePage, we check if the page requested is index.html. If yes, we go ahead and execute. If not, we throw an error that there is no such page available.

    If you try to run the program now, everything will work perfectly fine since the values for both the function is correct. We are more concerned about what happens when the error is thrown.

    Both errors are of different kinds and need to be handled differently. The page not available error is a 404, page not found error. You must have seen this type of error in the number of sites when you request a URL that is not available.
    The second type “Phrase not found” error is a system notification error. It tells us that the system lacks a vocabulary of the dictionary and needs to be updated. Something like a 500 error code is much better suited in this condition.

    Since both of these errors happen at this particular line const page = makePage(‘index.html’);, it’s pretty difficult to differentiate them from one other and handle efficiently. Both of them belong to the Error class: new Error(“There is no such page”);

    Read More:  Node.js Lesson 17: Timers, Differences from Browser, ref and ref

    The possible solution in this scenario is to separate the classes that are handling these two errors using object-oriented programming principles and let them handle. Let’s see how we can do that.

    Creating two classes to handle both types of error

    We just saw the problem with using the Error class to handle two types of errors. An approachable solution is to create two classes PhraseError and HttpError for both functions respectively.

    For getPhrase function, we can do something like:

    function getPhrase(name) {  
      if (!phrases[name]) {  
        throw new PhraseError("There is no such phrase: " + name);  
      }  
      return phrases[name];  
    }

    Similarly, we can update makePage function like this:

    function makePage(url) {  
    
      if (url != 'index.html') {  
        throw new HttpError(404, "There is no such a page");  
      }
      return util.format("%s, %s!", getPhrase("hello"), getPhrase("world"));  
    }

    Note that we have added error code 404 to the constructor. Now, we can use inheritance to create these two error classes. Remember util.inherits function we learned earlier? We are going to use that here.

    First, create PhraseError class:

    function PhraseError(message) {  
      this.message = message;  
    }  
    util.inherits(PhraseError, Error);  
    PhraseError.prototype.name = 'PhraseError';

    Let’s create HttpError in a similar fashion:

    function HttpError(status, message) {  
      this.status = status;  
      this.message = message;  
    }  
    util.inherits(HttpError, Error);  
    HttpError.prototype.name = 'HttpError';

    These two classes are simply inheriting all the properties of the Error class while adding some extra functionality. I hope you’re with me on this until here.

    Let’s look at what properties we might need in the class we just created. One thing we surely need is a message, we want to print the error message to the user. The next thing we might need is the error name. This info is also helpful for the developer to understand what type of error he is dealing and it’s best to print that along with the error message. The third important thing is the stack, we will talk about it later in this article. Let’s update our code to support these two error classes.

    const phrases = {
        "hello": "Hello",
        "world": "World"
    };
    
    // message name stack
    function PhraseError(message) {
        this.message = message;
    }
    util.inherits(PhraseError, Error);
    PhraseError.prototype.name = 'PhraseError';
    
    
    function HttpError(status, message) {
        this.status = status;
        this.message = message;
    }
    util.inherits(HttpError, Error);
    HttpError.prototype.name = 'HttpError';
    
    
    function getPhrase(name) {
        if (!phrases[name]) {
            throw new PhraseError("There is no such phrase: " + name);
        }
        return phrases[name];
    }
    
    function makePage(url) {
        if (url != 'index.html') {
            throw new HttpError(404, "There is no such page");
        }
        return util.format("%s, %s!", getPhrase("*****"), getPhrase("world"));
    }
    
    try {
        const page = makePage('index');
        console.log(page);
    } catch (e) {
        if (e instanceof HttpError) {
            console.log(e.status, e.message);
        } else {
            console.error("Error %sn message: %sn stack: %s", e.name, e.message, e.stack);
        }
    }

    Here, we are intentionally passing the wrong phrase and file name to see what happens when we encounter an error. Now, let’s talk about the stack.

    Read More:  React vs. Angular: Choosing The Right Tools for Your Next Project

    Add stack trace to know where the error occurred

    So far, we got everything working fine. The only thing left is to print a stack trace. The error name and message alone are not enough to debug a problem, we also want to know where exactly the error occurred to pinpoint the issue. Luckily, the Error class comes in handy in this situation and provides us a function to print a stack trace. Let’s see how:

    function PhraseError(message) {
        this.message = message;
        Error.captureStackTrace(this); // add this line to print stack trace
    }

    This command acquires the current stack, i.e. a consequence of requests put together that save it to this in the current code place, which means in the error object location. Let us take a look at what we’ve got now. Right now the system has outputted stack – the place, where it all occurred. But if we look carefully, the error happened exactly here:

    throw new PhraseError("There is no such a phrase: " + name);

    We are not interested in what is happening inside PhraseError, we want to know how we reached this line and what went wrong in the process.

    captureStackTrace() comes with a second argument which we can use to get our desired stack trace.

    Error.captureStackTrace(this, HttpError);
    
    // OR
    
    Error.captureStackTrace(this, PhraseError);

    This should work fine now. We learned how to use inherited error object to display appropriate error info as well as the stack trace. This is all for this article. See you in the next article.

    This lesson coding can be downloaded from here

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Mohammad Shad Mirza
    • X (Twitter)
    • LinkedIn

    JavaScript lover working on React Native and committed to simplifying code for beginners. Apart from coding and blogging, I like spending my time sketching or writing with a cup of tea.

    Related Posts

    Mastering REST APIs: Essential Techniques for Programmers

    December 18, 2024

    Streamlining Resource Allocation for Enhanced Project Success

    December 18, 2024

    Crafting Interactive User Interfaces Using JavaScript Techniques

    December 17, 2024

    Comments are closed.

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    Vue December 3, 2020

    Building Web Apps with Vue 3 composition API + Typescript + Vuex(4.0)

    In this tutorial, we are going to create a task management application to demonstrate how to build applications with the new Vue 3 composition API, typescript, and Vuex(4.0). Furthermore, we will explore Vuex(4.0) practically.

    22. Long Polling Chat, POST Reading. Pt 2.

    November 1, 2016

    The Best Work Tools for Remote Teams — Part 1: Cloud & Productivity

    April 16, 2019

    Top Lead Generation Strategies for MSPs in 2025

    May 3, 2025

    Categories

    • AI & Automation
    • Angular
    • ASP.NET
    • AWS
    • B2B Leads
    • Beginners
    • Blogs
    • Business Growth
    • Case Studies
    • Comics
    • Consultation
    • Content & Leadership
    • CSS
    • Development
    • Django
    • E-commerce & Retail
    • Entrepreneurs
    • Entrepreneurship
    • Events
    • Express.js
    • Facebook Ads
    • Finance & Fintech
    • Flask
    • Flutter
    • Franchising
    • Funnel Strategy
    • Git
    • GraphQL
    • Home Services Marketing
    • Influencer & Community
    • Interview
    • Java
    • Java Spring
    • JavaScript
    • Job
    • Laravel
    • Lead Generation
    • Legal & Compliance
    • LinkedIn
    • Machine Learning
    • Marketing Trends
    • Medical Marketing
    • MSP Lead Generation
    • MSP Marketing
    • NestJS
    • Next.js
    • Node.js
    • Node.js Lessons
    • Paid Advertising
    • PHP
    • Podcasts
    • POS Tutorial
    • Programming
    • Programming
    • Python
    • React
    • React Lessons
    • React Native
    • React Native Lessons
    • Recruitment
    • Remote Job
    • SaaS & Tech
    • SEO & Analytics
    • Soshace
    • Startups
    • Swarm Intelligence
    • Tips
    • Trends
    • Vue
    • Wiki
    • WordPress
    Top Posts

    Learn JavaScript and React with the TOP JavaScript YouTube Channels

    JavaScript May 16, 2019

    Testing Laravel Applications Like a Pro with PHPUnit

    Laravel December 4, 2020

    Nodejs Lesson 16: Internals of Nodejs: Event Loop

    Node.js February 5, 2021

    Advanced Mapmaking: Using d3, d3-scale and d3-zoom With Changing Data to Create Sophisticated Maps

    JavaScript March 11, 2020

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    About Us
    About Us

    Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

    7901 4th St N, Suite 28690
    Saint Petersburg, FL 33702-4305
    Phone: 1(877)SOSHACE

    Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
    Our Picks
    LinkedIn

    Strategic LinkedIn Techniques for Real Estate Lead Generation

    JavaScript

    Web Development Newsletters: JavaScript, React, Vue, Angular Email Newsletters

    Express.js

    Securing Node.js Applications with JWT and Passport.js

    Most Popular

    Maximizing LinkedIn: Top Tools for Lead Generation and Automation

    LinkedIn

    Заметка про распорядок дня

    Wiki

    Leveraging Crowdfunding: A Strategic Guide for Startups

    Entrepreneurship
    © 2025 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.