1.0.0 • Published 1 year ago

@riculum/js-errors v1.0.0

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

JS-Errors

A simple middleware for handling HTTP errors

Install

npm install @riculum/js-errors

Example

Have a look at examples

RouterMiddleware

import express from "express"
import AuthController from "../controllers/AuthController.js";
import {ErrorMiddleware, NotFoundError} from "@riculum/js-errors"

const router = express.Router()

//Define all routes
router.post('/login', AuthController.login)
router.post('/logout', AuthController.logout)

//Throw an error if the URL cannot be resolved
router.use((req, res, next) => {
    next(new NotFoundError("The requested url was not found on this server"))
})

//Handles all errors that are passed downwards
router.use(ErrorMiddleware.handleError)

export default router

AuthController

import {UnauthorizedError} from "@riculum/js-errors"

export default class AuthController {
    static async login(req, res, next) {
        try {
            const {email, password} = req.body

            //Check if user exists
            if (!email || !password) {
                throw new UnauthorizedError("email or password are missing")
            }

        } catch (e) {
            //Passing the exception to Error handling
            next(e)
        }
    }

    static logout(req, res, next) {
        try {
            //Do stuff
        } catch (e) {
            //Passing the exception to Error handling
            next(e)
        }
    }
}

List of all errors

Status CodeError
400BadRequest
401Unauthorized
402PaymentRequired
403Forbidden
404NotFound
405MethodNotAllowed
406NotAcceptable
407ProxyAuthenticationRequired
408RequestTimeout
409Conflict
410Gone
411LengthRequired
412PreconditionFailed
413PayloadTooLarge
414URITooLong
415UnsupportedMediaType
416RangeNotSatisfiable
417ExpectationFailed
418ImATeapot
422UnprocessableEntity
425TooEarly
426UpgradeRequired
428PreconditionRequired
429TooManyRequests
431RequestHeaderFieldsTooLarge
451UnavailableForLegalReasons
500InternalServerError
501NotImplemented
502BadGateway
503ServiceUnavailable
504GatewayTimeout
505HTTPVersionNotSupported
506VariantAlsoNegotiates
507InsufficientStorage
508LoopDetected
510NotExtended
511NetworkAuthenticationRequired

Bugreport & Contribution

If you find a bug, please either create a ticket in GitHub, or initiate a pull request

Versioning

We adhere to semantic (major.minor.patch) versioning (https://semver.org/). This means that:

  • Patch (x.x.patch) versions fix bugs
  • Minor (x.minor.x) versions introduce new, backwards compatible features or improve existing code.
  • Major (major.x.x) versions introduce radical changes which are not backwards compatible.

In your automation or procedure you can always safely update patch & minor versions without the risk of your application failing.