Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/pfrazee/zerr
custom js error construction
https://github.com/pfrazee/zerr
Last synced: 11 days ago
JSON representation
custom js error construction
- Host: GitHub
- URL: https://github.com/pfrazee/zerr
- Owner: pfrazee
- Created: 2015-09-13T18:14:03.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2016-02-07T21:48:47.000Z (almost 9 years ago)
- Last Synced: 2024-12-12T08:51:35.434Z (17 days ago)
- Language: JavaScript
- Size: 5.86 KB
- Stars: 4
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# ZErr
Custom JS error creator that subclasses `Error`, sets `.name` `.stack` and `.message`, and provides simple interpolation to construct error messages.
```js
var zerr = require('zerr')// first param: error name
// second param: string template for error messages (substitutes '%' with args in constructor)
var BadParam = zerr('BadParam', '% is an invalid parameter. Expected %.')// using the created error:
try { throw new BadParam('x', 'y') }
catch (e) {
console.log(e.name) // => 'BadParamError'
console.log(e.message) // => 'x is an invalid parameter. Expected y.'
console.log(e.stack) // => 'BadParamError: x is an invalid parameter. Expected y.\nat repl:1:13...'
console.log(e instanceof Error) // => true
console.log(e instanceof BadParam) // => true
}// the `new` is optional
throw BadParam('x', 'y')// if no string template is given, zerr will just use the constructor's param as the message
var BadParam = zerr('BadParam')
try { throw new BadParam('x is bad') }
catch (e) {
console.log(e.message) // => 'x is bad'
}// if you pass an error as the first param to the constructor, zerr will add its stack to the stack history
// this helps you follow the trail of an exception that is caught, and then rethrown
// (taken from https://github.com/dominictarr/explain-error)
try { throw new BadParam(new BadParam('earlier error'), 'later error') }
catch (e) {
console.log(e.stack) /* =>
BadPararmError: later error
at repl:1:7
BadPararmError: earlier error
at repl:1:15
*/
}
```