Skip to content

Commit 05963ae

Browse files
committed
Add a 'noExceptions' method to swallow errors
1 parent 3f7572b commit 05963ae

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,11 @@ parseJson('garbage') // more useful error message
3535
Works just like `JSON.parse`, but will include a bit more information when an
3636
error happens. This throws a `JSONParseError`.
3737

38+
#### <a name="parse"></a> `parse.noExceptions(txt, reviver = null)`
39+
40+
Works just like `JSON.parse`, but will return `undefined` rather than
41+
throwing an error.
42+
3843
#### <a name="jsonparseerror"></a> `class JSONParseError(er, text, context = 20, caller = null)`
3944

4045
Extends the JavaScript `SyntaxError` class to parse the message and provide

index.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,3 +89,9 @@ const stripBOM = txt => String(txt).replace(/^\uFEFF/, '')
8989

9090
module.exports = parseJson
9191
parseJson.JSONParseError = JSONParseError
92+
93+
parseJson.noExceptions = (txt, reviver) => {
94+
try {
95+
return JSON.parse(stripBOM(txt), reviver)
96+
} catch (e) {}
97+
}

test/index.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,3 +185,16 @@ t.test('json parse error class', t => {
185185

186186
t.end()
187187
})
188+
189+
t.test('parse without exception', t => {
190+
const bad = 'this is not json'
191+
t.equal(parseJson.noExceptions(bad), undefined, 'does not throw')
192+
const obj = { this: 'is json' }
193+
const good = JSON.stringify(obj)
194+
t.deepEqual(parseJson.noExceptions(good), obj, 'parses json string')
195+
const buf = Buffer.from(good)
196+
t.deepEqual(parseJson.noExceptions(buf), obj, 'parses json buffer')
197+
const bom = Buffer.concat([Buffer.from([0xEF, 0xBB, 0xBF]), buf])
198+
t.deepEqual(parseJson.noExceptions(bom), obj, 'parses json buffer with bom')
199+
t.end()
200+
})

0 commit comments

Comments
 (0)