Create a Basic Framework with Express (Part 1.1)

·

1 min read

Table of contents

No heading

No headings in the article.

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

We will make it something like this

throw new ServerError({ message: 'This is a major issue!!' })
  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