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!!' })
- Create a new folder exceptions
-
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 }
-
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) } }) ...
Now go to
localhost:3000/error
to see the 500 server error
Top comments (0)