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

Top comments (0)