Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Create errors that can be both thrown and returned. Make error handling easier for both JavaScript and TypeScript.

License

NotificationsYou must be signed in to change notification settings

SMBCheeky/error-object

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

26 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Licensedeno.bundlejs.comnpm downloadsGitHub last commitGitHub stars

TL;DR

  • Install the packagenpm install @smbcheeky/error-object
  • WriteErrorObject.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

Installation

npm install @smbcheeky/error-object

yarn add @smbcheeky/error-object

Description

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 acode and amessage values
  • It can have a numberCode, not just a string code
  • set default values for the generic and fallback error objects viaErrorObject.DEFAULT_GENERIC_CODE andErrorObject.DEFAULT_GENERIC_MESSAGE
  • set a default domain for all errors viaErrorObject.DEFAULT_DOMAIN
  • UseErrorObject.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
  • Usedetails,domain andtag to customize the error object and help easily distinguish between differenterrors

ErrorObject.from

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:.error and.force
  • .error represents the error, if it can be created, otherwise it isundefined
  • .force represents 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 optionscheckInputObjectForValues andcheckInputObjectForTypes andcheckInputObjectForKeys
  • then the objects checks for an object array atpathToErrors, 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 toErrorObject.from()
  • thepathToCode,pathToNumberCode,pathToMessage,pathToDetails andpathToDomain options are used to mapvalues to their associated field, if found
  • for all fields other thannumberCode, 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
  • fornumberCode, if a value is found and it is a number different thanNaN, it is saved
  • thetransform function 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 ofErrorSummary | ErrorObjectErrorResult array
  • 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 detailedprocessingErrors which includes the summaries and the errors that were triggered during the process,theraw object that was used as in input for the ErrorObject.from() call and thenextErrors array which allows forall errors to be saved on one single error object for later use

Usage & Examples

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]

FAQ

How do I use paths? Are they absolute?

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']

How do I use paths? Can I get the raw contents of a path and process it later?

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

Stars

Watchers

Forks


[8]ページ先頭

©2009-2025 Movatter.jp