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

@serverduty/http-errors

v0.1.3

Published

Streamlined predefined HTTP response functions for Express

Downloads

1

Readme

http-errors

github stars npm version npm downloads

@serverduty/http-errors offers a straightforward and efficient way to handle HTTP errors in your Express applications, making your code cleaner and more maintainable.

Usage

Importing the Package

You can import the entire set of HTTP error functions or individual functions based on your requirements.

Importing All Functions

import httpErrors from '@serverduty/http-errors'

With this import, you can use any of the error functions using the httpErrors object:

app.get('/example', (req, res) => {
  // Use any error function
  httpErrors.notFound(res, { message: 'This is a 404 error message' })
})

Importing Individual Functions

import { notFound, unauthorized } from '@serverduty/http-errors'

This allows you to use only the imported functions:

app.get('/example', (req, res) => {
  // Directly use the imported function
  notFound(res, { message: 'Not Found Error' })
})

Using Error Functions in Express

The error functions are designed to be used in an Express application. Here's how you can use them in your routes or middleware:

app.get('/user/:id', (req, res) => {
  const user = getUserById(req.params.id)
  if (!user) {
    return httpErrors.notFound(res, { message: 'User not found' })
  }
  res.json(user)
})

app.post('/login', (req, res) => {
  const { username, password } = req.body
  if (!authenticate(username, password)) {
    return httpErrors.unauthorized(res, { message: 'Invalid credentials' })
  }
  // proceed with login logic
})

Customizing Error Messages

You can pass a custom message or additional data as the second argument to any error function:

app.get('/restricted', (req, res) => {
  if (!req.user.isAdmin) {
    return httpErrors.forbidden(res, { message: 'Access denied', reason: 'Not an admin' })
  }
  // continue with admin-only logic
})

This flexibility allows you to provide more context in your error responses, making them more informative for the client.

Supported Error Functions

| Status Code | Status Message | Description | Function Name | |-------------|----------------------------------|---------------------------------------------------|---------------------------------------| | 400 | Bad Request | The server cannot or will not process the request due to an apparent client error. | badRequest | | 401 | Unauthorized | Authentication is required and has failed or has not yet been provided. | unauthorized | | 402 | Payment Required | Reserved for future use. | paymentRequired | | 403 | Forbidden | The request was valid, but the server is refusing action. | forbidden | | 404 | Not Found | The requested resource could not be found. | notFound | | 405 | Method Not Allowed | A request method is not supported for the requested resource. | methodNotAllowed | | 406 | Not Acceptable | The requested resource is capable of generating only content not acceptable according to the Accept headers. | notAcceptable | | 407 | Proxy Authentication Required | The client must first authenticate itself with the proxy. | proxyAuthenticationRequired | | 408 | Request Timeout | The server timed out waiting for the request. | requestTimeout | | 409 | Conflict | The request could not be completed due to a conflict with the current state of the resource. | conflict | | 410 | Gone | The resource requested is no longer available and will not be available again. | gone | | 411 | Length Required | The request did not specify the length of its content, which is required by the requested resource. | lengthRequired | | 412 | Precondition Failed | The server does not meet one of the preconditions that the requester put on the request. | preconditionFailed | | 413 | Payload Too Large | The request is larger than the server is willing or able to process. | payloadTooLarge | | 414 | URI Too Long | The URI provided was too long for the server to process. | uriTooLong | | 415 | Unsupported Media Type | The request entity has a media type which the server or resource does not support. | unsupportedMediaType | | 416 | Range Not Satisfiable | The client has asked for a portion of the file, but the server cannot supply that portion. | rangeNotSatisfiable | | 417 | Expectation Failed | The server cannot meet the requirements of the Expect request-header field. | expectationFailed | | 418 | I'm a teapot | A whimsical response used in some HTTP applications. | imATeapot | | 422 | Unprocessable Entity | The request was well-formed but was unable to be followed due to semantic errors. | unprocessableEntity | | 425 | Too Early | Indicates that the server is unwilling to risk processing a request that might be replayed. | tooEarly | | 426 | Upgrade Required | The client should switch to a different protocol. | upgradeRequired | | 428 | Precondition Required | The origin server requires the request to be conditional. | preconditionRequired | | 429 | Too Many Requests | The user has sent too many requests in a given amount of time. | tooManyRequests | | 431 | Request Header Fields Too Large | The server is unwilling to process the request because either an individual header field, or all the header fields collectively, are too large. | requestHeaderFieldsTooLarge | | 451 | Unavailable For Legal Reasons | The server is denying access to the resource as a consequence of a legal demand. | unavailableForLegalReasons | | 500 | Internal Server Error | A generic error message, given when an unexpected condition was encountered. | internalServerError | | 501 | Not Implemented | The server either does not recognize the request method, or it lacks the ability to fulfill the request. | notImplemented | | 502 | Bad Gateway | The server was acting as a gateway or proxy and received an invalid response from the upstream server. | badGateway | | 503 | Service Unavailable | The server is currently unavailable (because it is overloaded or down for maintenance). | serviceUnavailable | | 504 | Gateway Timeout | The server was acting as a gateway or proxy and did not receive a timely response from the upstream server. | gatewayTimeout | | 505 | HTTP Version Not Supported | The server does not support the HTTP protocol version used in the request. | httpVersionNotSupported | | 506 | Variant Also Negotiates | Transparent content negotiation for the request results in a circular reference. | variantAlsoNegotiates | | 507 | Insufficient Storage | The server is unable to store the representation needed to complete the request. | insufficientStorage | | 508 | Loop Detected | The server detected an infinite loop while processing the request. | loopDetected | | 510 | Not Extended | Further extensions to the request are required for the server to fulfill it. | notExtended | | 511 | Network Authentication Required | The client needs to authenticate to gain network access. | networkAuthenticationRequired |

License

The MIT License (MIT)

Copyright 2023 ServerDuty Limited

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.