perr
Portable errors for Javascript
npm install perr
usage
//// Perr lets you create "portable" error objects to use throughout// your applications.// const plainError = 'something happened'plainErrorstatusCode = 500StringplainError // Error: something happenedJSON// {// "statusCode": 500// } //// Now, let's try to create a portable error out of this.// perr.convert(err, props) takes an Error instance and an// optional "props" object, and returns an Error instance,// modified to be JSON stringifiable// const portableError1 = perrStringportableError1 // Error: something happenedJSON// {// "name": "Error",// "message": "something happened",// "stack": "Error: something happened\n at <anonymous>:1:20"// } //// Even if the plain error's properties are enumerable, perr.convert(err, props)// does not pick them onto the portable error unless you explicitly specify// so.// This is to prevent surprises, since with modules like `got()`, errors can// have additional properties which aren't necessarily enumerable.// const portableError2 = perrStringportableError2 // Error: something happenedJSON// {// "name": "Error",// "message": "something happened",// "stack": "Error: something happened\n at <anonymous>:1:20",// "statusCode": 500,// "somethingElse": "nice"// } //// perr.toObj(err, props) creates a plain object from an error.// This is a more efficient equivalent of calling// JSON.parse(JSON.stringify(perr.toObj(err, props)))//// This works on both plain and "portable" errors.// const plainErrObj = perr// {// "name": "Error",// "message": "something happened",// "stack": "Error: something happened\n at <anonymous>:1:20",// "somethingElse": "nice"// } //// perr.toErr(obj) converts an error object to a portable Error// instance. The error will be run through the guaranteed-error module,// to fill in name, message, and stack, if they are missing.//// If obj is a simple string, that will be the error's `message`.// const createdError1 = perrcreatedError1 instanceof Error // truecreatedError1stack // Error: something happened\n at <anonymous>:1:20createdError1somethingElse // nice const createdError2 = perrcreatedError2name // ErrorcreatedError2message // <No error message provided>createdError2stack // asdf: something happened const createdError3 = perrcreatedError3name // ErrorcreatedError3message // something happenedcreatedError3stack // Error: something happened\n at <unknown>