- Notifications
You must be signed in to change notification settings - Fork0
Create errors that can be both thrown and returned. Make error handling easier for both JavaScript and TypeScript.
License
SMBCheeky/error-object
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
- Install the package
npm install @smbcheeky/error-object - Write
ErrorObject.from(<pick an api response with an error>).force.verboseLog('LOG')and use the info provided tomap your error - Switch the .force with .error, and now you have an error object
- 🎉
- oh... and check theplayground file
npm install @smbcheeky/error-object
yarn add @smbcheeky/error-object
The ErrorObject class is made to extendError enabling checks likeerrorObject instanceof Error orerrorObject instanceof ErrorObject. TheErrorObject class is backwards compatible withError and introduces a fewnew features:
- It can be thrown or returned, you choose.
- It can be valid only if it contains a
codeand amessagevalues - It can have a numberCode, not just a string code
- set default values for the generic and fallback error objects via
ErrorObject.DEFAULT_GENERIC_CODEandErrorObject.DEFAULT_GENERIC_MESSAGE - set a default domain for all errors via
ErrorObject.DEFAULT_DOMAIN - Use
ErrorObject.generic()orErrorObject.withTag('TAG')to create an error from thin air - Use
.isGeneric(),.isFallback()and.hasTag()to check if the error is a generic error, a fallback error orhas a specific tag - Chain call setters like
.setCode(),.setNumberCode(),.setMessage(),.setDetails(),.setDomain(),.setTag()to modify the errorobject at any moment - Setters can receive a value or a transform function, facilitating access to the current value while you modify theproperty
- Chain logs like
.log(tag),.debugLog(tag),.verboseLog(tag)to log information about the error objectinline - Use
.description()or.toString()to get a human-readable description of the error - Use
details,domainandtagto customize the error object and help easily distinguish between differenterrors
UseErrorObject.from(<anything>) to create errors from any input:
- you can pass an object or a caught error to it, and it will try its best to create an error from it
ErrorObject.from(<anything>)returns an object with two properties:.errorand.force.errorrepresents the error, if it can be created, otherwise it isundefined.forcerepresents the error, if it can be created, otherwise it is going to return aErrorObject.fallback()error
The processing of the ErrorObject is done in a few steps, based on theErrorObjectBuildOptions:
- first the initial object is checked via the options
checkInputObjectForValuesandcheckInputObjectForTypesandcheckInputObjectForKeys - then the objects checks for an object array at
pathToErrors, which could be an array of errors - if an error array is found, the process will consider all other paths relative to the objects in the error array found
- if an error array is not found, the process will consider all other paths absolute to the initial objectpassed to
ErrorObject.from() - the
pathToCode,pathToNumberCode,pathToMessage,pathToDetailsandpathToDomainoptions are used to mapvalues to their associated field, if found - for all fields other than
numberCode, if a value is found and is a string, it is saved as is, but if it is an arrayor an object it will be JSON.stringify'ed and saved as a string - for
numberCode, if a value is found and it is a number different thanNaN, it is saved - the
transformfunction is used to transform the found values by the parsing process into the error object - the transform function has access to all pre-transformation values and also the initial object (object inside theerrors array or initial object)
- everything gets processed into a list of
ErrorSummary | ErrorObjectErrorResultarray - it contains everything, from error strings custom-made to be as distinct and easy to read as possible, to selfdocumenting summaries of what values are found, at which path, if an errors object was found, etc.
- the count of the list is meant to be an indication of how many input objects were found and processed, as each of themshould become an error object
- in the last step of the process, the list is filtered down and a single error object is created, with everything bakedin
- think detailed
processingErrorswhich includes the summaries and the errors that were triggered during the process,therawobject that was used as in input for the ErrorObject.from() call and thenextErrorsarray which allows forall errors to be saved on one single error object for later use
For a guide on how to use the library, please check the first detailed example intheplayground file.
newErrorObject({code:'',message:'Something went wrong.',domain:'auth'}).debugLog('LOG');ErrorObject.from({code:'',message:'Something went wrong',domain:'auth'})?.force?.debugLog('LOG');// Example 12 output://// [LOG] Something went wrong. [auth]// {// "code": "",// "message": "Something went wrong.",// "domain": "auth"// }//// [LOG] Something went wrong [auth]// {// "code": "",// "message": "Something went wrong",// "domain": "auth"// }
constresponse={statusCode:400,headers:{'Content-Type':'application/json',},body:'{"error":"Invalid input data","code":400}',};ErrorObject.from(JSON.parse(response?.body),{pathToNumberCode:['code'],pathToMessage:['error'],}).force?.debugLog('LOG');// Example 6 output://// [LOG] Invalid input data [400]// {// "code": "400",// "numberCode": 400,// "message": "Invalid input data"// }
/* * You could have a file called `errors.ts` in each of your modules/folders and * define a function like `createAuthError2()` that returns an error object with * the correct message and domain. */constAuthMessageResolver=(beforeTransform:ErrorObjectTransformState):ErrorObjectTransformState=>{// Quick tip: Make all messages slightly different, to make it easy// to find the right one when debugging, even in productionletmessage:string|undefined;switch(beforeTransform.code){case'generic':message='Something went wrong';break;case'generic-again':message='Something went wrong. Please try again.';break;case'generic-network':message='Something went wrong. Please check your internet connection and try again.';break;default:message='Something went wrong.';}return{ ...beforeTransform, message};};constcreateAuthError2=(code:string)=>{returnErrorObject.from({ code,domain:'auth',},{transform:AuthMessageResolver,});};createAuthError2('generic')?.error?.log('1');createAuthError2('generic-again')?.error?.log('2');createAuthError2('generic-network')?.error?.log('3');createAuthError2('invalid-code')?.error?.log('4');// Example 2 output://// [1] Something went wrong [auth/generic]// [2] Something went wrong. Please try again. [auth/generic-again]// [3] Something went wrong. Please check your internet connection and try again. [auth/generic-network]// [4] Something went wrong. [auth/invalid-code]
To support inputs containing arrays of errors as well as single errors, all paths are treated initially as absolute (from theinput root), but if an array of errors is detected, it will consider each element found the new root input object. Devshave achoice: set the "pathToErrors" option as empty, and then map only the first error (highly not recommended), or adjustthe paths to be relative to the objects inside the detected errors array.
How do I use paths? I sometimes get the error code in anerror object, and sometimes in the root object...
You can usepathToCode: addPrefixPathVariants('error', ['code']), orpathToCode: ['error.code']
Yes, you can. You can use paths likeerror.details.0 to get a raw value, and then process it later using thetransform option.If the value is not a string, it will be converted to a string usingJSON.stringify to ensure everything works asintended.Remember, for an ErrorObject to be created, it needs at least a code and a message, and both are required to be stringvalues.
About
Create errors that can be both thrown and returned. Make error handling easier for both JavaScript and TypeScript.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Uh oh!
There was an error while loading.Please reload this page.