Skip to content

Commit cda94b5

Browse files
committed
Wrap JSON literal parsing errors.
1 parent 624fcc6 commit cda94b5

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

lib/fromRdf.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
*/
44
'use strict';
55

6+
const JsonLdError = require('./JsonLdError');
67
const graphTypes = require('./graphTypes');
78
const types = require('./types');
89
const util = require('./util');
@@ -288,7 +289,14 @@ function _RDFToObject(o, useNativeTypes) {
288289
}
289290
if(type === RDF_JSON_LITERAL) {
290291
type = '@json';
291-
rval['@value'] = JSON.parse(rval['@value']);
292+
try {
293+
rval['@value'] = JSON.parse(rval['@value']);
294+
} catch(e) {
295+
throw new JsonLdError(
296+
'JSON literal could not be parsed.',
297+
'jsonld.InvalidJsonLiteral',
298+
{code: 'invalid JSON literal', value: rval['@value'], cause: e});
299+
}
292300
}
293301
// use native types for certain xsd types
294302
if(useNativeTypes) {

tests/misc.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -519,3 +519,20 @@ describe('js keywords', () => {
519519
assert.deepStrictEqual(e, ex);
520520
});
521521
});
522+
523+
describe.only('literal JSON', () => {
524+
it('handles error', done => {
525+
const d =
526+
'_:b0 <ex:p> "bogus"^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#JSON> .'
527+
;
528+
const p = jsonld.fromRDF(d);
529+
assert(p instanceof Promise);
530+
p.then(() => {
531+
assert.fail();
532+
}).catch(e => {
533+
assert(e);
534+
assert.equal(e.name, 'jsonld.InvalidJsonLiteral');
535+
done();
536+
});
537+
});
538+
});

0 commit comments

Comments
 (0)