• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Exceptions
2
3## Overview
4
5### Base type
6
7All exceptions inherit from class `json::exception` (which in turn inherits from `std::exception`). It is used as the base class for all exceptions thrown by the `basic_json` class. This class can hence be used as "wildcard" to catch exceptions.
8
9```plantuml
10std::exception <|-- json::exception
11json::exception <|-- json::parse_error
12json::exception <|-- json::invalid_iterator
13json::exception <|-- json::type_error
14json::exception <|-- json::out_of_range
15json::exception <|-- json::other_error
16
17interface std::exception {}
18
19class json::exception {
20    + const int id
21    + const char* what() const
22}
23
24class json::parse_error {
25    + const std::size_t byte
26}
27```
28
29### Switch off exceptions
30
31Exceptions are used widely within the library. They can, however, be switched off with either using the compiler flag `-fno-exceptions` or by defining the symbol `JSON_NOEXCEPTION`. In this case, exceptions are replaced by `abort()` calls. You can further control this behavior by defining `JSON_THROW_USER` (overriding `#!cpp throw`), `JSON_TRY_USER` (overriding `#!cpp try`), and `JSON_CATCH_USER` (overriding `#!cpp catch`).
32
33Note that `JSON_THROW_USER` should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior.
34
35??? example
36
37    The code below switches off exceptions and creates a log entry with a detailed error message in case of errors.
38
39    ```cpp
40    #include <iostream>
41
42    #define JSON_TRY_USER if(true)
43    #define JSON_CATCH_USER(exception) if(false)
44    #define JSON_THROW_USER(exception)                           \
45        {std::clog << "Error in " << __FILE__ << ":" << __LINE__ \
46                   << " (function " << __FUNCTION__ << ") - "    \
47                   << (exception).what() << std::endl;           \
48         std::abort();}
49
50    #include <nlohmann/json.hpp>
51    ```
52
53## Parse errors
54
55This exception is thrown by the library when a parse error occurs. Parse errors
56can occur during the deserialization of JSON text, CBOR, MessagePack, as well
57as when using JSON Patch.
58
59Exceptions have ids 1xx.
60
61!!! info "Byte index"
62
63    Member `byte` holds the byte index of the last read character in the input
64    file.
65
66    For an input with n bytes, 1 is the index of the first character and n+1
67    is the index of the terminating null byte or the end of file. This also
68    holds true when reading a byte vector (CBOR or MessagePack).
69
70??? example
71
72    The following code shows how a `parse_error` exception can be caught.
73
74    ```cpp
75    --8<-- "examples/parse_error.cpp"
76    ```
77
78    Output:
79
80    ```
81    --8<-- "examples/parse_error.output"
82    ```
83
84
85### json.exception.parse_error.101
86
87This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member `byte` indicates the error position.
88
89!!! failure "Example message"
90
91    Input ended prematurely:
92
93    ```
94    [json.exception.parse_error.101] parse error at 2: unexpected end of input; expected string literal
95    ```
96
97    No input:
98
99    ```
100    [json.exception.parse_error.101] parse error at line 1, column 1: syntax error while parsing value - unexpected end of input; expected '[', '{', or a literal
101    ```
102
103    Control character was not escaped:
104
105    ```
106    [json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0009 (HT) must be escaped to \u0009 or \\; last read: '"<U+0009>'"
107    ```
108
109    String was not closed:
110
111    ```
112    [json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: missing closing quote; last read: '"'
113    ```
114
115    Invalid number format:
116
117    ```
118    [json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid number; expected '+', '-', or digit after exponent; last read: '1E'
119    ```
120
121    `\u` was not be followed by four hex digits:
122
123    ```
124    [json.exception.parse_error.101] parse error at line 1, column 6: syntax error while parsing value - invalid string: '\u' must be followed by 4 hex digits; last read: '"\u01"'
125    ```
126
127    Invalid UTF-8 surrogate pair:
128
129    ```
130    [json.exception.parse_error.101] parse error at line 1, column 13: syntax error while parsing value - invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF; last read: '"\uD7FF\uDC00'"
131    ```
132
133    Invalid UTF-8 byte:
134
135    ```
136    [json.exception.parse_error.101] parse error at line 3, column 24: syntax error while parsing value - invalid string: ill-formed UTF-8 byte; last read: '"vous \352t'
137    ```
138
139!!! tip
140
141    - Make sure the input is correctly read. Try to write the input to standard output to check if, for instance, the input file was successfully openened.
142    - Paste the input to a JSON validator like <http://jsonlint.com> or a tool like [jq](https://stedolan.github.io/jq/).
143
144### json.exception.parse_error.102
145
146JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point.
147
148!!! failure "Example message"
149
150    ```
151    parse error at 14: missing or wrong low surrogate
152    ```
153
154### json.exception.parse_error.103
155
156Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid.
157
158!!! failure "Example message"
159
160    ```
161    parse error: code points above 0x10FFFF are invalid
162    ```
163
164### json.exception.parse_error.104
165
166[RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects.
167
168!!! failure "Example message"
169
170    ```
171    [json.exception.parse_error.104] parse error: JSON patch must be an array of objects
172    ```
173
174### json.exception.parse_error.105
175
176An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors.
177
178!!! failure "Example message"
179
180    ```
181    [json.exception.parse_error.105] parse error: operation 'add' must have member 'value'
182    ```
183    ```
184    [json.exception.parse_error.105] parse error: operation 'copy' must have string member 'from'
185    ```
186    ```
187    [json.exception.parse_error.105] parse error: operation value 'foo' is invalid
188    ```
189
190### json.exception.parse_error.106
191
192An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`.
193
194!!! failure "Example message"
195
196    ```
197    [json.exception.parse_error.106] parse error: array index '01' must not begin with '0'
198    ```
199
200### json.exception.parse_error.107
201
202A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character.
203
204!!! failure "Example message"
205
206    ```
207    [json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'foo'
208    ```
209
210### json.exception.parse_error.108
211
212In a JSON Pointer, only `~0` and `~1` are valid escape sequences.
213
214!!! failure "Example message"
215
216    ```
217    [json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'
218    ```
219
220### json.exception.parse_error.109
221
222A JSON Pointer array index must be a number.
223
224!!! failure "Example message"
225
226    ```
227    [json.exception.parse_error.109] parse error: array index 'one' is not a number
228    ```
229    ```
230    [json.exception.parse_error.109] parse error: array index '+1' is not a number
231    ```
232
233### json.exception.parse_error.110
234
235When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read.
236
237!!! failure "Example message"
238
239    ```
240    [json.exception.parse_error.110] parse error at byte 5: syntax error while parsing CBOR string: unexpected end of input
241    ```
242    ```
243    [json.exception.parse_error.110] parse error at byte 2: syntax error while parsing UBJSON value: expected end of input; last byte: 0x5A
244    ```
245
246### json.exception.parse_error.112
247
248Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read.
249
250!!! failure "Example message"
251
252    ```
253    [json.exception.parse_error.112] parse error at byte 1: syntax error while parsing CBOR value: invalid byte: 0x1C
254    ```
255
256### json.exception.parse_error.113
257
258While parsing a map key, a value that is not a string has been read.
259
260!!! failure "Example message"
261
262    ```
263    [json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR string: expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0xFF
264    ```
265    ```
266    [json.exception.parse_error.113] parse error at byte 2: syntax error while parsing MessagePack string: expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0xFF
267    ```
268    ```
269    [json.exception.parse_error.113] parse error at byte 2: syntax error while parsing UBJSON char: byte after 'C' must be in range 0x00..0x7F; last byte: 0x82
270    ```
271
272### json.exception.parse_error.114
273
274The parsing of the corresponding BSON record type is not implemented (yet).
275
276!!! failure "Example message"
277
278    ```
279    [json.exception.parse_error.114] parse error at byte 5: Unsupported BSON record type 0xFF
280    ```
281
282### json.exception.parse_error.115
283
284A UBJSON high-precision number could not be parsed.
285
286!!! failure "Example message"
287
288    ```
289    [json.exception.parse_error.115] parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A
290    ```
291
292## Iterator errors
293
294This exception is thrown if iterators passed to a library function do not match
295the expected semantics.
296
297Exceptions have ids 2xx.
298
299??? example
300
301    The following code shows how an `invalid_iterator` exception can be caught.
302
303    ```cpp
304    --8<-- "examples/invalid_iterator.cpp"
305    ```
306
307    Output:
308
309    ```
310    --8<-- "examples/invalid_iterator.output"
311    ```
312
313### json.exception.invalid_iterator.201
314
315The iterators passed to constructor `basic_json(InputIT first, InputIT last)` are not compatible, meaning they do not belong to the same container. Therefore, the range (`first`, `last`) is invalid.
316
317!!! failure "Example message"
318
319    ```
320    [json.exception.invalid_iterator.201] iterators are not compatible
321    ```
322
323### json.exception.invalid_iterator.202
324
325In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion.
326
327!!! failure "Example message"
328
329    ```
330    [json.exception.invalid_iterator.202] iterator does not fit current value
331    ```
332    ```
333    [json.exception.invalid_iterator.202] iterators first and last must point to objects
334    ```
335
336### json.exception.invalid_iterator.203
337
338Either iterator passed to function `erase(IteratorType` first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from.
339
340!!! failure "Example message"
341
342    ```
343    [json.exception.invalid_iterator.203] iterators do not fit current value
344    ```
345
346### json.exception.invalid_iterator.204
347
348When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (`begin(),` `end()),` because this is the only way the single stored value is expressed. All other ranges are invalid.
349
350!!! failure "Example message"
351
352    ```
353    [json.exception.invalid_iterator.204] iterators out of range
354    ```
355
356### json.exception.invalid_iterator.205
357
358When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the `begin()` iterator, because it is the only way to address the stored value. All other iterators are invalid.
359
360!!! failure "Example message"
361
362    ```
363    [json.exception.invalid_iterator.205] iterator out of range
364    ```
365
366### json.exception.invalid_iterator.206
367
368The iterators passed to constructor `basic_json(InputIT first, InputIT last)` belong to a JSON null value and hence to not define a valid range.
369
370!!! failure "Example message"
371
372    ```
373    [json.exception.invalid_iterator.206] cannot construct with iterators from null
374    ```
375
376### json.exception.invalid_iterator.207
377
378The `key()` member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key.
379
380!!! failure "Example message"
381
382    ```
383    [json.exception.invalid_iterator.207] cannot use key() for non-object iterators
384    ```
385
386
387### json.exception.invalid_iterator.208
388
389The `operator[]` to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
390
391!!! failure "Example message"
392
393    ```
394    [json.exception.invalid_iterator.208] cannot use operator[] for object iterators
395    ```
396
397### json.exception.invalid_iterator.209
398
399The offset operators (`+`, `-`, `+=`, `-=`) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
400
401!!! failure "Example message"
402
403    ```
404    [json.exception.invalid_iterator.209] cannot use offsets with object iterators
405    ```
406
407### json.exception.invalid_iterator.210
408
409The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (`first`, `last`) is invalid.
410
411!!! failure "Example message"
412
413    ```
414    [json.exception.invalid_iterator.210] iterators do not fit
415    ```
416
417### json.exception.invalid_iterator.211
418
419The iterator range passed to the insert function must not be a subrange of the container to insert to.
420
421!!! failure "Example message"
422
423    ```
424    [json.exception.invalid_iterator.211] passed iterators may not belong to container
425    ```
426
427### json.exception.invalid_iterator.212
428
429When two iterators are compared, they must belong to the same container.
430
431!!! failure "Example message"
432
433    ```
434    [json.exception.invalid_iterator.212] cannot compare iterators of different containers
435    ```
436
437### json.exception.invalid_iterator.213
438
439The order of object iterators cannot be compared, because JSON objects are unordered.
440
441!!! failure "Example message"
442
443    ```
444    [json.exception.invalid_iterator.213] cannot compare order of object iterators
445    ```
446
447### json.exception.invalid_iterator.214
448
449Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to `begin()`.
450
451!!! failure "Example message"
452
453    ```
454    [json.exception.invalid_iterator.214] cannot get value
455    ```
456
457
458## Type errors
459
460This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics.
461
462Exceptions have ids 3xx.
463
464??? example
465
466    The following code shows how a `type_error` exception can be caught.
467
468    ```cpp
469    --8<-- "examples/type_error.cpp"
470    ```
471
472    Output:
473
474    ```
475    --8<-- "examples/type_error.output"
476    ```
477
478### json.exception.type_error.301
479
480To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead.
481
482!!! failure "Example message"
483
484    ```
485    [json.exception.type_error.301] cannot create object from initializer list
486    ```
487
488### json.exception.type_error.302
489
490During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types.
491
492!!! failure "Example message"
493
494    ```
495    [json.exception.type_error.302] type must be object, but is null
496    ```
497    ```
498    [json.exception.type_error.302] type must be string, but is object
499    ```
500
501### json.exception.type_error.303
502
503To retrieve a reference to a value stored in a `basic_json` object with `get_ref`, the type of the reference must match the value type. For instance, for a JSON array, the `ReferenceType` must be `array_t &`.
504
505!!! failure "Example message"
506
507    ```
508    [json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is object
509    ```
510    ```
511    [json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is number"
512    ```
513
514### json.exception.type_error.304
515
516The `at()` member functions can only be executed for certain JSON types.
517
518!!! failure "Example message"
519
520    ```
521    [json.exception.type_error.304] cannot use at() with string
522    ```
523    ```
524    [json.exception.type_error.304] cannot use at() with number
525    ```
526
527### json.exception.type_error.305
528
529The `operator[]` member functions can only be executed for certain JSON types.
530
531!!! failure "Example message"
532
533    ```
534    [json.exception.type_error.305] cannot use operator[] with a string argument with array
535    ```
536    ```
537    [json.exception.type_error.305] cannot use operator[] with a numeric argument with object
538    ```
539
540### json.exception.type_error.306
541
542The `value()` member functions can only be executed for certain JSON types.
543
544!!! failure "Example message"
545
546    ```
547    [json.exception.type_error.306] cannot use value() with number
548    ```
549
550### json.exception.type_error.307
551
552The `erase()` member functions can only be executed for certain JSON types.
553
554!!! failure "Example message"
555
556    ```
557    [json.exception.type_error.307] cannot use erase() with string
558    ```
559
560### json.exception.type_error.308
561
562The `push_back()` and `operator+=` member functions can only be executed for certain JSON types.
563
564!!! failure "Example message"
565
566    ```
567    [json.exception.type_error.308] cannot use push_back() with string
568    ```
569
570### json.exception.type_error.309
571
572The `insert()` member functions can only be executed for certain JSON types.
573
574!!! failure "Example message"
575
576    ```
577    [json.exception.type_error.309] cannot use insert() with array
578    ```
579    ```
580    [json.exception.type_error.309] cannot use insert() with number
581    ```
582
583### json.exception.type_error.310
584
585The `swap()` member functions can only be executed for certain JSON types.
586
587!!! failure "Example message"
588
589    ```
590    [json.exception.type_error.310] cannot use swap() with number
591    ```
592
593### json.exception.type_error.311
594
595The `emplace()` and `emplace_back()` member functions can only be executed for certain JSON types.
596
597!!! failure "Example message"
598
599    ```
600    [json.exception.type_error.311] cannot use emplace() with number
601    ```
602    ```
603    [json.exception.type_error.311] cannot use emplace_back() with number
604    ```
605
606### json.exception.type_error.312
607
608The `update()` member functions can only be executed for certain JSON types.
609
610!!! failure "Example message"
611
612    ```
613    [json.exception.type_error.312] cannot use update() with array
614    ```
615
616### json.exception.type_error.313
617
618The `unflatten` function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined.
619
620!!! failure "Example message"
621
622    ```
623    [json.exception.type_error.313] invalid value to unflatten
624    ```
625
626### json.exception.type_error.314
627
628The `unflatten` function only works for an object whose keys are JSON Pointers.
629
630!!! failure "Example message"
631
632    Calling `unflatten()` on an array `#!json [1,2,3]`:
633
634    ```
635    [json.exception.type_error.314] only objects can be unflattened
636    ```
637
638### json.exception.type_error.315
639
640The `unflatten()` function only works for an object whose keys are JSON Pointers and whose values are primitive.
641
642!!! failure "Example message"
643
644    Calling `unflatten()` on an object `#!json {"/1", [1,2,3]}`:
645
646    ```
647    [json.exception.type_error.315] values in object must be primitive
648    ```
649
650### json.exception.type_error.316
651
652The `dump()` function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded.
653
654!!! failure "Example message"
655
656    Calling `dump()` on a JSON value containing an ISO 8859-1 encoded string:
657    ```
658    [json.exception.type_error.316] invalid UTF-8 byte at index 15: 0x6F
659    ```
660
661!!! tip
662
663    - Store the source file with UTF-8 encoding.
664    - Pass an error handler as last parameter to the `dump()` function to avoid this exception:
665        - `json::error_handler_t::replace` will replace invalid bytes sequences with `U+FFFD`
666        - `json::error_handler_t::ignore` will silently ignore invalid byte sequences
667
668### json.exception.type_error.317
669
670The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw `true` or `null` JSON object cannot be serialized to BSON)
671
672!!! failure "Example message"
673
674    Serializing `#!json null` to BSON:
675    ```
676    [json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is null
677    ```
678    Serializing `#!json [1,2,3]` to BSON:
679    ```
680    [json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is array
681    ```
682
683!!! tip
684
685    Encapsulate the JSON value in an object. That is, instead of serializing `#!json true`, serialize `#!json {"value": true}`
686
687
688## Out of range
689
690This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys.
691
692Exceptions have ids 4xx.
693
694??? example
695
696    The following code shows how an `out_of_range` exception can be caught.
697
698    ```cpp
699    --8<-- "examples/out_of_range.cpp"
700    ```
701
702    Output:
703
704    ```
705    --8<-- "examples/out_of_range.output"
706    ```
707
708### json.exception.out_of_range.401
709
710The provided array index `i` is larger than `size-1`.
711
712!!! failure "Example message"
713
714    ```
715    array index 3 is out of range
716    ```
717
718### json.exception.out_of_range.402
719
720The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it.
721
722!!! failure "Example message"
723
724    ```
725    array index '-' (3) is out of range
726    ```
727
728### json.exception.out_of_range.403
729
730The provided key was not found in the JSON object.
731
732!!! failure "Example message"
733
734    ```
735    key 'foo' not found
736    ```
737
738### json.exception.out_of_range.404
739
740A reference token in a JSON Pointer could not be resolved.
741
742!!! failure "Example message"
743
744    ```
745    unresolved reference token 'foo'
746    ```
747
748### json.exception.out_of_range.405
749
750The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value.
751
752!!! failure "Example message"
753
754    ```
755    JSON pointer has no parent
756    ```
757
758### json.exception.out_of_range.406
759
760A parsed number could not be stored as without changing it to NaN or INF.
761
762!!! failure "Example message"
763
764    ```
765    number overflow parsing '10E1000'
766    ```
767
768### json.exception.out_of_range.407
769
770UBJSON and BSON only support integer numbers up to 9223372036854775807.
771
772!!! failure "Example message"
773
774    ```
775    number overflow serializing '9223372036854775808'
776    ```
777
778!!! note
779
780    Since version 3.9.0, integer numbers beyond int64 are serialized as high-precision UBJSON numbers, and this exception does not further occur.
781
782### json.exception.out_of_range.408
783
784The size (following `#`) of an UBJSON array or object exceeds the maximal capacity.
785
786!!! failure "Example message"
787
788    ```
789    excessive array size: 8658170730974374167
790    ```
791
792### json.exception.out_of_range.409
793
794Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string.
795
796!!! failure "Example message"
797
798    ```
799    BSON key cannot contain code point U+0000 (at byte 2)
800    ```
801
802## Further exceptions
803
804This exception is thrown in case of errors that cannot be classified with the
805other exception types.
806
807Exceptions have ids 5xx.
808
809??? example
810
811    The following code shows how an `other_error` exception can be caught.
812
813    ```cpp
814    --8<-- "examples/other_error.cpp"
815    ```
816
817    Output:
818
819    ```
820    --8<-- "examples/other_error.output"
821    ```
822
823### json.exception.other_error.501
824
825A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
826
827!!! failure "Example message"
828
829    Executing `#!json {"op":"test", "path":"/baz", "value":"bar"}` on `#!json {"baz": "qux"}`:
830
831    ```
832    [json.exception.other_error.501] unsuccessful: {"op":"test","path":"/baz","value":"bar"}
833    ```
834