1.1.0 • Published 5 years ago

houston-errors v1.1.0

Weekly downloads
7
License
MIT
Repository
github
Last release
5 years ago

Houston-Errors, "we have a problem"

The Houston creates and returns a JavaScript Error, uses http errors and makes easy to add informations on it. (for while just in 400x, 500x, but you can create custom errors). All errors uses the same function called DefaultError which centralizes everything, that way makes easy handling errors. Also have an option to get default http errors objects by name, and from it get name, string and code. All errors are logged, and the best part is freedom to listen all errors and handle them by HoustonErrorEvents. It also have some integrations such as Sequelize.

Code style: airbnb node (scoped with tag) Jest coverage

Example of application (piece found over web)

app.get('/users/:id', (req, res) => {
  const userId = req.params.id
  if (!userId) {
    return res.sendStatus(400).json({
      error: 'Missing id'
    })
  }

  Users.get(userId, (err, user) => {
    if (err) {
      return res.sendStatus(500).json(err)
    }

    res.send(users)
  })
})

Using Houston

const { BadRequest } = require('houston-errors).houstonClientErrors;
const { InternalServerError } = require('houston-errors).houstonServerErrors;
app.get('/users/:id', (req, res) => {
  try {
	const userId = req.params.id
	if (!userId) { BadRequest({ message: 'Missing id' }); }
	Users.get(userId, (err, user) => {
	if (err) { InternalServerError({ data: err }); }
	res.send(users);
  } catch (error) {
      return res.sendStatus(error.code).json(error)
  }

Houston-Errors

All function listed above use on of DefaultError from houston-errors.

DefaultError(houstonError, optionals)

It will create a JS Error object, add name, code, error and the optionals (message, data). All the functions will returns the DefaultError.

  • houstonError - Objects which can ben found in in houstonClientErrors, houstonServerErrors.
  • optionals - optional object where: - message is a custom message which will be show in error.
    • data - additional error information (it can be object or string).

Usage Example

    const { DefaultError } = require('houston-errors').houston;
    const { BAD_REQUEST } = require('houston-errors').houstonClientErrors;
    const sendMessage = 'This is Houston. Say again, please';
    DefaultError(BAD_REQUEST, {
        message: sendMessage,
        data: '{Lousma: houston, we have a problem.}',
    });

CustomError(optionals)

It is also possible create your custom errors setting things like code, error, name, message and data.

  • optionals - optional object where: - code is the code of error (default: 500). - error is the error type (default: Internal Server Error). - name the name of error (default: INTERNAL_SERVER_ERROR). - message is a custom message (default: if not defined it will be removed of object).
    • data - additional error information (it can be object or string, default: if not defined it will be removed of object).

Usage Example

    const { CustomError } = require('houston-errors').houston;
    const sendMessage = 'This is Houston. Say again, please';
    const lovellData = {lovell: 'We have had a MAIN B BUS UNDERVOLT'};
    const errorDef = 'houston, we have a problem';
    CustomError({
        code: 406,
        error: errorDef,
        name:'Lousma',
        message: sendMessage,
        data: lovellData,
    });

HoustonErrorEvents

You can also listen the HoustonErrorEvents which will emit all houstonError by the event 'weHaveAProblem' then handle it for whatever you want for a better custom application.

Usage Example

    const { HoustonErrorEvent } = require('houston-errors').houston;

    HoustonErrorEvent.on('weHaveAProblem', (error) => {
      //..code
    });

HoustonClientErrors

It is possible to import the the client errors by the name bellow and you get get any of them. They are an object with code, string and name.

CodeStringName
400Bad RequestBAD_REQUEST
401UnauthorizedUNAUTHORIZED
402Payment RequiredPAYMENT_REQUIRED
403ForbiddenFORBIDDEN
404Not FoundNOT_FOUND
405Method Not AllowedMETHOD_NOT_ALLOWED
406Not AcceptableNOT_ACCEPTABLE
407Proxy Authentication RequiredPROXY_AUTHENTICATION_REQUIRED
408Request TimeoutREQUEST_TIMEOUT
409ConflictCONFLICT
410GoneGONE
411Length RequiredLENGTH_REQUIRED
412Precondition FailedPRECONDITION_FAILED
413Payload Too LargePAYLOAD_TOO_LARGE
414Uri Too longURI_TOO_LONG
415Unsupported Media TypeUNSUPPORTED_MEDIA_TYPE
416Range Not SatisfiableRANGE_NOT_SATISFIABLE
417Expectation FailedEXPECTATION_FAILED
418Im a TeapotIM_A_TEAPOT
421Misdirected RequestMISDIRECTED_REQUEST
422Unprocessable EntityUNPROCESSABLE_ENTITY
423LockedLOCKED
424Failed DependencyFAILED_DEPENDENCY
425Unordered CollectionUNORDERED_COLLECTION
426Upgrade RequiredUPGRADE_REQUIRED
428Precondition RequiredPRECONDITION_REQUIRED
429Too Many RequestsTOO_MANY_REQUESTS
431Request Header Fields Too LargeREQUEST_HEADER_FIELDS_TOO_LARGE
451Unavailable for Legal ReqsonsUNAVAILABLE_FOR_LEGAL_REASONS

Usage example

  const { NOT_FOUND } = require('houston-errors').houstonClientErrors;
  console.log(`code: ${NOT_FOUND.code}, name: ${NOT_FOUND.name}, error: ${NOT_FOUND.error} `);

It is also possible use functions which returns a JavaScript Error and contains keys like name, error, code, message and data. By default, those methods just returns code, name and error. The available functions are listed bellow.

FunctionName
BadRequest
Unauthorized
PaymentRequired
Forbidden
NotFound
MethodNotAllowed
NotAcceptable
ProxyAuthenticationRequired
RequestTimeout
Conflict
Gone
LengthRequired
PreconditionFailed
PayloadTooLarge
UriTooLong
UnsupportedMediaType
RangeNotSatisfiable
ExpectionFailed
ImATeapot
MisdirectedRequest
UnprocessableEntity
Locked
FailedDependency
UnorderedCollection
UpgradeRequired
PreconditionRequired
TooManyRequests
RequestHeaderFieldsTooLarge
UnavailableForLegalReasons

All those functions above returns a DefaultError and have the structure like:

FunctionName(optionals)

  • optionals - optional object where: - message is a custom message which will be show in error.
    • data - additional error information (it can be object or string).

Usage example

const { NotFound } = require('houston-errors').houstonClientErrors;

try {
    NotFound();
  } catch (error) {
    console.log(error.code)
  }

Setting message and data.

const { NotFound } = require('houston-errors').houstonClientErrors;

try {
    NotFound({message: 'custom message', data: 'some custom object or message'});
  } catch (error) {
    console.log(error.message);
  }

HoustonServerErrors

It is possible to import the the server errors by the name bellow and you get get any of them. They are an object with code, string and name.

CodeStringName
500Internal Server ErrorINTERNAL_SERVER_ERROR
501Not ImplementedNOT_IMPLEMENTED
502Bad GatewayBAD_GATEWAY
503Service UnavailableSERVICE_UNAVAILABLE
504Gateway TimeoutGATEWAY_TIMEOUT
505HTTP Version Not SupportedHTTP_VERSION_NOT_SUPPORTED
506Variant Also NegotiatesVARIANT_ALSO_NEGOTIATES
507Insufficient StorageINSUFFICIENT_STORAGE
508Loop DetectedLOOP_DETECTED
509Bandwidth Limit ExceededBANDWIDTH_LIMIT_EXCEEDED
510Not ExtendedNOT_EXTENDEED
511Network Authentication RequiredNETWORK_AUTHENTICATION_REQUIRED

Usage example

  const { INTERNAL_SERVER_ERROR } = require('houston-errors').houstonServerErrors;
  console.log(`code: ${INTERNAL_SERVER_ERROR.code}, name: ${INTERNAL_SERVER_ERROR.name}, error: ${INTERNAL_SERVER_ERROR.error} `);

It is also possible use functions which returns a JavaScript Error and contains keys like name, error, code, message and data. By default, those methods just returns code, name and error. The available functions are listed bellow.

FunctionName
Internal Server Error
Not Implemented
Bad Gateway
Service Unavailable
Gateway Timeout
HTTP Version Not Supported
Variant Also Negotiates
Insufficient Storage
Loop Detected
Bandwidth Limit Exceeded
Not Extended
Network Authentication Required

All those functions above returns a DefaultError and have the structure like:

FunctionName(optionals)

  • optionals - optional object where: - message is a custom message which will be show in error.
    • data - additional error information (it can be object or string).

Usage example

const { InternalServerError } = require('houston-errors').houstonServerErrors;

try {
    InternalServerError();
  } catch (error) {
    console.log(error.code)
  }

Setting message and data.

const { InternalServerError } = require('houston-errors').houstonServerErrors;

try {
    InternalServerError({message: 'custom message', data: 'some custom object or message'});
  } catch (error) {
    console.log(error.message);
  }

Apollo13

It is just an additional function and objects.

CodeStringName
403User is not activeUSER_NOT_ACTIVE
403License is not activeLICENSE_IS_NOT_ACTIVE
403Renew license requiredRENEW_LICENSE_REQUIRED
401No token foundNO_TOKEN
401Invalid tokenINVALID_TOKEN
401Expired tokenEXPIRED_TOKEN
406Empty required paramEMPTY_REQUIRED_PARAM

SequelizeError

If you use Sequelize, the basic of error will be integrated by function bellow.

FunctionName
SequelizeError

SequelizeError, Usage Example

const { SequelizeError } = require('houston-errors').apollo13;
// Sequelize Model instance.
const User = require('../db/models/index').users;

try {
function createUser(userParams) {
  try {
    const params = userParams;
    const user = await User.create(params);
    return user;
  } catch (error) {
    // It will create an object Error; You must return if is in different paths.
    return SequelizeError(error);
  }
1.1.0

5 years ago

1.0.11

6 years ago

1.0.10

6 years ago

1.0.9

6 years ago

1.0.8

6 years ago

1.0.7

6 years ago

1.0.6

6 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago