0.1.3 • Published 1 year ago

@serverduty/http-errors v0.1.3

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

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 CodeStatus MessageDescriptionFunction Name
400Bad RequestThe server cannot or will not process the request due to an apparent client error.badRequest
401UnauthorizedAuthentication is required and has failed or has not yet been provided.unauthorized
402Payment RequiredReserved for future use.paymentRequired
403ForbiddenThe request was valid, but the server is refusing action.forbidden
404Not FoundThe requested resource could not be found.notFound
405Method Not AllowedA request method is not supported for the requested resource.methodNotAllowed
406Not AcceptableThe requested resource is capable of generating only content not acceptable according to the Accept headers.notAcceptable
407Proxy Authentication RequiredThe client must first authenticate itself with the proxy.proxyAuthenticationRequired
408Request TimeoutThe server timed out waiting for the request.requestTimeout
409ConflictThe request could not be completed due to a conflict with the current state of the resource.conflict
410GoneThe resource requested is no longer available and will not be available again.gone
411Length RequiredThe request did not specify the length of its content, which is required by the requested resource.lengthRequired
412Precondition FailedThe server does not meet one of the preconditions that the requester put on the request.preconditionFailed
413Payload Too LargeThe request is larger than the server is willing or able to process.payloadTooLarge
414URI Too LongThe URI provided was too long for the server to process.uriTooLong
415Unsupported Media TypeThe request entity has a media type which the server or resource does not support.unsupportedMediaType
416Range Not SatisfiableThe client has asked for a portion of the file, but the server cannot supply that portion.rangeNotSatisfiable
417Expectation FailedThe server cannot meet the requirements of the Expect request-header field.expectationFailed
418I'm a teapotA whimsical response used in some HTTP applications.imATeapot
422Unprocessable EntityThe request was well-formed but was unable to be followed due to semantic errors.unprocessableEntity
425Too EarlyIndicates that the server is unwilling to risk processing a request that might be replayed.tooEarly
426Upgrade RequiredThe client should switch to a different protocol.upgradeRequired
428Precondition RequiredThe origin server requires the request to be conditional.preconditionRequired
429Too Many RequestsThe user has sent too many requests in a given amount of time.tooManyRequests
431Request Header Fields Too LargeThe server is unwilling to process the request because either an individual header field, or all the header fields collectively, are too large.requestHeaderFieldsTooLarge
451Unavailable For Legal ReasonsThe server is denying access to the resource as a consequence of a legal demand.unavailableForLegalReasons
500Internal Server ErrorA generic error message, given when an unexpected condition was encountered.internalServerError
501Not ImplementedThe server either does not recognize the request method, or it lacks the ability to fulfill the request.notImplemented
502Bad GatewayThe server was acting as a gateway or proxy and received an invalid response from the upstream server.badGateway
503Service UnavailableThe server is currently unavailable (because it is overloaded or down for maintenance).serviceUnavailable
504Gateway TimeoutThe server was acting as a gateway or proxy and did not receive a timely response from the upstream server.gatewayTimeout
505HTTP Version Not SupportedThe server does not support the HTTP protocol version used in the request.httpVersionNotSupported
506Variant Also NegotiatesTransparent content negotiation for the request results in a circular reference.variantAlsoNegotiates
507Insufficient StorageThe server is unable to store the representation needed to complete the request.insufficientStorage
508Loop DetectedThe server detected an infinite loop while processing the request.loopDetected
510Not ExtendedFurther extensions to the request are required for the server to fulfill it.notExtended
511Network Authentication RequiredThe 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.

0.1.3

1 year ago

0.1.2

2 years ago

0.1.1

2 years ago

0.1.0

2 years ago