fatmatto / throwable-http-errors

Throwable HTTP errors for node apis

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Build Status

Throwable HTTP errors

Throwable HTTP errors for node APIs.

Installation

npm i throwable-http-errors

Usage

const Errors = require('throwable-http-errors')

// for example, using express.js
router.post('/', wrap(async (req, res, next) => {
  try {
    if (!validatePet(req.body)) {
      throw new Errors.BadRequest()
    }

    const pet = await PetsController.create(req.body)
    res.send({ status: true, data: pet })
  } catch (e) {
    return next(e)
  }
}))

Reason

Before async/await, I was used to send errors to the main error catching middleware just by running

return next(new Errors.BadRequest())

Now, with async/await we can leverage try/catch blocks to handle errors. While I'm not quite happy with having try/catch blocks in every route, having await for promises improves code readablity (and quality in my opinion) a lot.

About

Throwable HTTP errors for node apis

License:MIT License


Languages

Language:JavaScript 96.9%Language:Shell 3.1%