DEV Community

Bryan
Bryan

Posted on • Originally published at hashnode.com

Create a Basic Framework with Express (Part 1.1)

In Part 1, error handling was created. Let's make it easier to throw errors.
Instead of

let error = new Error('This is a major issue!!')
error.statusCode = 500
throw error
Enter fullscreen mode Exit fullscreen mode

We will make it something like this

throw new ServerError({ message: 'This is a major issue!!' })
Enter fullscreen mode Exit fullscreen mode
  1. Create a new folder exceptions
  2. Create ServerError.js in the exceptions folder

    class ServerError extends Error {
      constructor(resource) {
        super()
        this.name = this.constructor.name // good practice
        this.statusCode = 500
        this.message = resource ? resource.message : 'Server Error'
      }
    }
    module.exports = {
      ServerError
    }
    
  3. Edit index.js, on how to use it

    // index.js
    ...
    const { ServerError } = require('./exceptions/ServerError')
    ...
    app.get('/error', async (req, res, next) => {
        try {
            throw new ServerError()
            // or
           // throw new ServerError({ message: 'A huge mistake happened!' })
        } catch (error) {
            return next(error)
        }
    })
    ...
    
  4. Now go to localhost:3000/error to see the 500 server error

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay