npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

throwlhos

v1.0.1

Published

Thorw error objects directly from express response

Downloads

1,274

Readme

Throwlhos

Throws error objects with status and code

throw Error('What the heck goes here?...')

You do not know exactly what to throw?! We've got you covered! image License: MIT npm version Build Status Coverage Status Downloads

npm

Installation

The latest version is available at: https://www.npmjs.com/package/throwlhos

Use your favorite package manager to install. For instance:

  yarn add throwlhos

Basic Usage

import throwlhos from 'throwlhos'
import { Request, Response } from 'express'

class FooBarController {
  async index(request: Request, response: Response) {
    console.log(throwlhos.err_internalServerError())
    // IThrowlhos object
  }
}

Above code prompts the following output:

{
  code: 500,
  status: 'INTERNAL_SERVER_ERROR',
  message: 'Internal Server Error'
} 

err_* methods accept two optional parameters:

message?: string | null
errors?: any

Returned throwlhos object type exaplained:

export type IThrowlhos = {
  code: number
  status: string
  message: string
  errors: any
}
  • code: Number value of HTTP Status Code

  • status: String value of HTTP Status Name

  • message: Message given at first parameter or HTTP Status Name human-readable if none or null is given.

  • errors: Anything given as the second parameter. It's undefined if no value is given.

Throwlhos as an express middleware

You can use throwlhos as an express middleware:

app.use(throwlhos.middlware)

Since throwlhos overwrites Express interface, you can find throwlhos err_* methods directly in express response!

Consider the following code which is an express middlware:

import throwlhos from 'throwlhos'
import { Request, Response } from 'express'

class FooBarController {
  async index(request: Request, response: Response) {
    const throwlhos = response.err_internalServerError()
    return response.status(throwlhos.code).send(throwlhos)
  }
}

Outputs:

HTTP/1.1 500 INTERNAL_SERVER_ERROR
X-Powered-By: Express
errors-Type: application/json; charset=utf-8
{
  code: 500,
  status: 'INTERNAL_SERVER_ERROR',
  message: 'Internal Server Error'
} 

Usage with an express Error Handler (recommended)

If you want to quickly send an error response with your throwlhos use it with responserror.

Responserror handler will catch-all errors from any express middleware router in-between by using next(err) .

Full example:

  import throwlhos from 'throwlhos'
  import errorHandler from 'responserror'
  const app = express()
  const router = express.Router()
  router.post('/resources', (_, response: Response, next: NextFunction) => {
    try {
      throw response.err_forbidden('Access denied.. Sorry')
    } catch(err) {
      return next(err)
    }
  })
  app.use(throwlhos.middlware)
  app.use(router)
  app.use(errorHandler)

POST /resources outputs:

HTTP/1.1 403 FORBIDDEN
X-Powered-By: Express
errors-Type: application/json; charset=utf-8
{
  code: 403,
  status: 'FORBIDDEN',
  message: 'Access denied.. Sorry',
  success: false
}

Available Methods

Throwlhos currently supports following methods:

err_multipleChoices // Multiple Choices
err_movedPermanently // Moved Permanently
err_movedTemporarily // Moved Temporarily
err_seeOther // See Other
err_notModified // Not Modified
err_useProxy // Use Proxy
err_temporaryRedirect // Temporary Redirect
err_permanentRedirect // Permanent Redirect
err_badRequest // Bad Request
err_unauthorized // Unauthorized
err_paymentRequired // Payment Required
err_forbidden // Forbidden
err_notFound // Not Found
err_methodNotAllowed // Method Not Allowed
err_notAcceptable // Not Acceptable
err_proxyAuthenticationRequired // Proxy Authentication Required
err_requestTimeout // Request Timeout
err_conflict // Conflict
err_gone // Gone
err_lengthRequired // Length Required
err_preconditionFailed // Precondition Failed
err_requestTooLong // Request Entity Too Large
err_requestUriTooLong // Request-URI Too Long
err_unsupportedMediaType // Unsupported Media Type
err_requestedRangeNotSatisfiable // Requested Range Not Satisfiable
err_expectationFailed // Expectation Failed
err_imATeapot // I'm a teapot
err_insufficientSpaceOnResource // Insufficient Space on Resource
err_methodFailure // Method Failure
err_misdirectedRequest // Misdirected Request
err_unprocessableEntity // Unprocessable Entity
err_locked // Locked
err_failedDependency // Failed Dependency
err_preconditionRequired // Precondition Required
err_tooManyRequests // Too Many Requests
err_requestHeaderFieldsTooLarge // Request Header Fields Too Large
err_unavailableForLegalReasons // Unavailable For Legal Reasons
err_internalServerError // Internal Server Error
err_notImplemented // Not Implemented
err_badGateway // Bad Gateway
err_serviceUnavailable // Service Unavailable
err_gatewayTimeout // Gateway Timeout
err_httpVersionNotSupported // HTTP Version Not Supported
err_insufficientStorage // Insufficient Storage
err_networkAuthenticationRequired // Network Authentication Required
err_custom // Custom Error (provide message, code and errors)

More

Special thanks to my fellow engineer Estanis as his words where my inspiration in the naming of the package.

Testing

Run the test suit with yarn test.

Contributing

If you want to contribute in any of theses ways:

  • Give your ideas or feedback
  • Question something
  • Point out a problem or issue
  • Enhance the code or its documentation
  • Help in any other way

You can (and should) open an issue or even a pull request.

Has this package been useful for you?

If so, you can contribute by giving it a Star ⭐ at the GitHub Repository!

Thanks for your interest in contributing to this repo!

Author

Luiz Felipe Zarco ([email protected])

License

This code is licensed under the MIT License. See the LICENSE.md file for more info.