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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay