GeniuCode Terminator Package - To handle different type of errors
npm install @geniucode/terminatorsh
npm i --save @geniucode/terminator
`
Versions that can be used
`sh
0.0.2 => npm i --save @geniucode/terminator@0.0.2
`API Documentation
Available Error Types | Status Code | Default Error
------------ | ------------- | -------------
BadRequestError | 400 | \[DEFAULT-ERROR] Bad Request
NotAuthorizedError | 401 | \[DEFAULT-ERROR] Not Authorized
PaymentRequiredError | 402 | \[DEFAULT-ERROR] Payment Is Required
ForbiddenError | 403 | \[DEFAULT-ERROR] Forbidden
NotFoundError | 404 | \[DEFAULT-ERROR] Not Found
InvalidHttpMethodError | 405 | \[DEFAULT-ERROR] Invalid HTTP Method
MethodNotAllowedError | 405 | \[DEFAULT-ERROR] Method Not Allowed
ProxyAuthRequiredError | 407 | \[DEFAULT-ERROR] Proxy Authentication Required
RequestTimeoutError | 408 | \[DEFAULT-ERROR] Request Timeout
ConflictError | 409 | \[DEFAULT-ERROR] Conflict Has Been Found
DuplicateIdConflictError | 409 | \[DEFAULT-ERROR] Duplicate Id
LargePayloadError | 413 | \[DEFAULT-ERROR] Payload Too Large
UnsupportedMediaTypeError | 415 | \[DEFAULT-ERROR] Unsupported Media Type
ValidationError (Unprocessable Entity) | 422 | \[DEFAULT-ERROR] There Was A Validation Error
ProtocolUpgradeRequiredError | 426 | \[DEFAULT-ERROR] Protocol Upgrade Required
TooManyRequestsError | 429 | \[DEFAULT-ERROR] Too Many Requests
InternalServerError | 500 | \[DEFAULT-ERROR] Internal Server
DatabaseConnectionError | 500 | \[DEFAULT-ERROR] Database Connection
NotImplementedError | 501 | \[DEFAULT-ERROR] Not implemented, server does not support the functionality required to fulfill the request.
GatewayTimeoutError | 504 | \[DEFAULT-ERROR] Gateway Timeout
ServiceUnavailableError | 503 | \[DEFAULT-ERROR] Service Unavailable
HttpVersionNotSupportedError | 505 | \[DEFAULT-ERROR] HTTP Version Not Supported
NOTES
RequestValidationError is different than ValidationError,
RequestValidationError gets an array as an argumentValidationError
Might occurs for example on cases as the following:
This username already existsNotFoundError
Item/Resource not foundUsage Demo 1 - Throw an Error without Log
`javascript
import { TErrors, TUtils} from '@geniucode/terminator';try{
throw new TErrors.BadRequestError("Demo error Message");
// Or throw a default message by using:
throw new TErrors.BadRequestError();
}
catch(error: any){
TUtils.throwError(error);
}
`Usage Demo 2 - Throw an Error and Log
`javascript
import { TErrors, TUtils} from '@geniucode/terminator';try{
throw new TErrors.BadRequestError("Check your fields");
}
catch(error: any){
TUtils.throwErrorAndLog(error);
// Error output message:
// Check your fields
// You can provide a prefix message for the error as the following
TUtils.throwErrorAndLog(error, '[Prefix-Message]-Your request is invalid');
// Error output message:
// [Prefix-Message]-Your request is invalid Check your fields
}
`Usage via app.ts file
`javascript
import { TMiddlewares } from '@geniucode/terminator';// Handle the thrown Errors
// and will end the response with the right status code depends on Error Type
app.use(TMiddlewares.errorHandler);
`Usage Example from a route in Express
`js
async (req: Request, res: Response) => { const {ticket, status} = req.body;
const sessionInfo = {ticket,status};
let session;
try {
session = await Session.build(sessionInfo).save();
const session = await Session.build(sessionInfo).save();
httpResponse.created(res, session, 'Session Created successfully');
} catch (error: any) {
// * VERY IMPORTANT *
// Notice here we are throwing always an error of type ConflictError,
// even though a different type of error might been thrown
const errorMsg =
Unable to create session:: ${error?.message};
throw new TErrors.ConflictError(errorMsg);
}
}
`Usage Example from a route in Express
`js
async (req: Request, res: Response) => { const {ticket, status} = req.body;
const sessionInfo = {ticket,status};
let session;
try {
session = await Session.build(sessionInfo).save();
const session = await Session.build(sessionInfo).save();
httpResponse.created(res, session, 'Session Created successfully');
} catch (error: any) {
// Very Important
// Thrown error is catched by app.use(TMiddlewares.errorHandler) from app.ts file
const errorMsg =
Unable to create session:: ${error?.message};
throw new TErrors.ConflictError(errorMsg);
}
}
`
An example Of how you would replace an existing code to the new one
`js
import { TErrors, TUtils } from '@geniucode/terminator';async (req: Request, res: Response) => {
const { message, agent, ticket } = req.body;
try {
if (!agent || !ticket) {
throw new TErrors.BadRequestError('Something went wrong');
// throw new BadRequestError('Something went wrong');
}
} catch (error: any) {
TUtils.throwErrorAndLog(error, 'Novelty-Error-service | ');
// TUtils.throwErrorAndLog is replacing all of the code bellow
// logger.error(error?.message);
// if (error instanceof BadRequestError) {
// throw new BadRequestError('Novelty-Error-service | ' + error?.message);
// } else {
// throw new Error('Novelty-Error-service | ' + error?.message);
// }
}
}
``