• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #pragma once
2 
3 #include <exception> // exception
4 #include <stdexcept> // runtime_error
5 #include <string> // to_string
6 #include <vector> // vector
7 
8 #include <nlohmann/detail/value_t.hpp>
9 #include <nlohmann/detail/string_escape.hpp>
10 #include <nlohmann/detail/input/position_t.hpp>
11 #include <nlohmann/detail/macro_scope.hpp>
12 
13 namespace nlohmann
14 {
15 namespace detail
16 {
17 ////////////////
18 // exceptions //
19 ////////////////
20 
21 /*!
22 @brief general exception of the @ref basic_json class
23 
24 This class is an extension of `std::exception` objects with a member @a id for
25 exception ids. It is used as the base class for all exceptions thrown by the
26 @ref basic_json class. This class can hence be used as "wildcard" to catch
27 exceptions.
28 
29 Subclasses:
30 - @ref parse_error for exceptions indicating a parse error
31 - @ref invalid_iterator for exceptions indicating errors with iterators
32 - @ref type_error for exceptions indicating executing a member function with
33                   a wrong type
34 - @ref out_of_range for exceptions indicating access out of the defined range
35 - @ref other_error for exceptions indicating other library errors
36 
37 @internal
38 @note To have nothrow-copy-constructible exceptions, we internally use
39       `std::runtime_error` which can cope with arbitrary-length error messages.
40       Intermediate strings are built with static functions and then passed to
41       the actual constructor.
42 @endinternal
43 
44 @liveexample{The following code shows how arbitrary library exceptions can be
45 caught.,exception}
46 
47 @since version 3.0.0
48 */
49 class exception : public std::exception
50 {
51   public:
52     /// returns the explanatory string
what() const53     const char* what() const noexcept override
54     {
55         return m.what();
56     }
57 
58     /// the id of the exception
59     const int id; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes)
60 
61   protected:
62     JSON_HEDLEY_NON_NULL(3)
exception(int id_,const char * what_arg)63     exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
64 
name(const std::string & ename,int id_)65     static std::string name(const std::string& ename, int id_)
66     {
67         return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
68     }
69 
70     template<typename BasicJsonType>
diagnostics(const BasicJsonType & leaf_element)71     static std::string diagnostics(const BasicJsonType& leaf_element)
72     {
73 #if JSON_DIAGNOSTICS
74         std::vector<std::string> tokens;
75         for (const auto* current = &leaf_element; current->m_parent != nullptr; current = current->m_parent)
76         {
77             switch (current->m_parent->type())
78             {
79                 case value_t::array:
80                 {
81                     for (std::size_t i = 0; i < current->m_parent->m_value.array->size(); ++i)
82                     {
83                         if (&current->m_parent->m_value.array->operator[](i) == current)
84                         {
85                             tokens.emplace_back(std::to_string(i));
86                             break;
87                         }
88                     }
89                     break;
90                 }
91 
92                 case value_t::object:
93                 {
94                     for (const auto& element : *current->m_parent->m_value.object)
95                     {
96                         if (&element.second == current)
97                         {
98                             tokens.emplace_back(element.first.c_str());
99                             break;
100                         }
101                     }
102                     break;
103                 }
104 
105                 case value_t::null: // LCOV_EXCL_LINE
106                 case value_t::string: // LCOV_EXCL_LINE
107                 case value_t::boolean: // LCOV_EXCL_LINE
108                 case value_t::number_integer: // LCOV_EXCL_LINE
109                 case value_t::number_unsigned: // LCOV_EXCL_LINE
110                 case value_t::number_float: // LCOV_EXCL_LINE
111                 case value_t::binary: // LCOV_EXCL_LINE
112                 case value_t::discarded: // LCOV_EXCL_LINE
113                 default:   // LCOV_EXCL_LINE
114                     break; // LCOV_EXCL_LINE
115             }
116         }
117 
118         if (tokens.empty())
119         {
120             return "";
121         }
122 
123         return "(" + std::accumulate(tokens.rbegin(), tokens.rend(), std::string{},
124                                      [](const std::string & a, const std::string & b)
125         {
126             return a + "/" + detail::escape(b);
127         }) + ") ";
128 #else
129         static_cast<void>(leaf_element);
130         return "";
131 #endif
132     }
133 
134   private:
135     /// an exception object as storage for error messages
136     std::runtime_error m;
137 };
138 
139 /*!
140 @brief exception indicating a parse error
141 
142 This exception is thrown by the library when a parse error occurs. Parse errors
143 can occur during the deserialization of JSON text, CBOR, MessagePack, as well
144 as when using JSON Patch.
145 
146 Member @a byte holds the byte index of the last read character in the input
147 file.
148 
149 Exceptions have ids 1xx.
150 
151 name / id                      | example message | description
152 ------------------------------ | --------------- | -------------------------
153 json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position.
154 json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON 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.
155 json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid.
156 json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects.
157 json.exception.parse_error.105 | parse error: operation must have string member 'op' | An 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.
158 json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`.
159 json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character.
160 json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences.
161 json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
162 json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read.
163 json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read.
164 json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read.
165 json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet).
166 json.exception.parse_error.115 | parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A | A UBJSON high-precision number could not be parsed.
167 
168 @note For an input with n bytes, 1 is the index of the first character and n+1
169       is the index of the terminating null byte or the end of file. This also
170       holds true when reading a byte vector (CBOR or MessagePack).
171 
172 @liveexample{The following code shows how a `parse_error` exception can be
173 caught.,parse_error}
174 
175 @sa - @ref exception for the base class of the library exceptions
176 @sa - @ref invalid_iterator for exceptions indicating errors with iterators
177 @sa - @ref type_error for exceptions indicating executing a member function with
178                     a wrong type
179 @sa - @ref out_of_range for exceptions indicating access out of the defined range
180 @sa - @ref other_error for exceptions indicating other library errors
181 
182 @since version 3.0.0
183 */
184 class parse_error : public exception
185 {
186   public:
187     /*!
188     @brief create a parse error exception
189     @param[in] id_       the id of the exception
190     @param[in] pos       the position where the error occurred (or with
191                          chars_read_total=0 if the position cannot be
192                          determined)
193     @param[in] what_arg  the explanatory string
194     @return parse_error object
195     */
196     template<typename BasicJsonType>
create(int id_,const position_t & pos,const std::string & what_arg,const BasicJsonType & context)197     static parse_error create(int id_, const position_t& pos, const std::string& what_arg, const BasicJsonType& context)
198     {
199         std::string w = exception::name("parse_error", id_) + "parse error" +
200                         position_string(pos) + ": " + exception::diagnostics(context) + what_arg;
201         return parse_error(id_, pos.chars_read_total, w.c_str());
202     }
203 
204     template<typename BasicJsonType>
create(int id_,std::size_t byte_,const std::string & what_arg,const BasicJsonType & context)205     static parse_error create(int id_, std::size_t byte_, const std::string& what_arg, const BasicJsonType& context)
206     {
207         std::string w = exception::name("parse_error", id_) + "parse error" +
208                         (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") +
209                         ": " + exception::diagnostics(context) + what_arg;
210         return parse_error(id_, byte_, w.c_str());
211     }
212 
213     /*!
214     @brief byte index of the parse error
215 
216     The byte index of the last read character in the input file.
217 
218     @note For an input with n bytes, 1 is the index of the first character and
219           n+1 is the index of the terminating null byte or the end of file.
220           This also holds true when reading a byte vector (CBOR or MessagePack).
221     */
222     const std::size_t byte;
223 
224   private:
parse_error(int id_,std::size_t byte_,const char * what_arg)225     parse_error(int id_, std::size_t byte_, const char* what_arg)
226         : exception(id_, what_arg), byte(byte_) {}
227 
position_string(const position_t & pos)228     static std::string position_string(const position_t& pos)
229     {
230         return " at line " + std::to_string(pos.lines_read + 1) +
231                ", column " + std::to_string(pos.chars_read_current_line);
232     }
233 };
234 
235 /*!
236 @brief exception indicating errors with iterators
237 
238 This exception is thrown if iterators passed to a library function do not match
239 the expected semantics.
240 
241 Exceptions have ids 2xx.
242 
243 name / id                           | example message | description
244 ----------------------------------- | --------------- | -------------------------
245 json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid.
246 json.exception.invalid_iterator.202 | iterator does not fit current value | In 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.
247 json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref 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.
248 json.exception.invalid_iterator.204 | iterators out of range | When 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 (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid.
249 json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid.
250 json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range.
251 json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The 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.
252 json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
253 json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
254 json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid.
255 json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to.
256 json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
257 json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
258 json.exception.invalid_iterator.214 | cannot get value | Cannot 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 @ref begin().
259 
260 @liveexample{The following code shows how an `invalid_iterator` exception can be
261 caught.,invalid_iterator}
262 
263 @sa - @ref exception for the base class of the library exceptions
264 @sa - @ref parse_error for exceptions indicating a parse error
265 @sa - @ref type_error for exceptions indicating executing a member function with
266                     a wrong type
267 @sa - @ref out_of_range for exceptions indicating access out of the defined range
268 @sa - @ref other_error for exceptions indicating other library errors
269 
270 @since version 3.0.0
271 */
272 class invalid_iterator : public exception
273 {
274   public:
275     template<typename BasicJsonType>
create(int id_,const std::string & what_arg,const BasicJsonType & context)276     static invalid_iterator create(int id_, const std::string& what_arg, const BasicJsonType& context)
277     {
278         std::string w = exception::name("invalid_iterator", id_) + exception::diagnostics(context) + what_arg;
279         return invalid_iterator(id_, w.c_str());
280     }
281 
282   private:
283     JSON_HEDLEY_NON_NULL(3)
invalid_iterator(int id_,const char * what_arg)284     invalid_iterator(int id_, const char* what_arg)
285         : exception(id_, what_arg) {}
286 };
287 
288 /*!
289 @brief exception indicating executing a member function with a wrong type
290 
291 This exception is thrown in case of a type error; that is, a library function is
292 executed on a JSON value whose type does not match the expected semantics.
293 
294 Exceptions have ids 3xx.
295 
296 name / id                     | example message | description
297 ----------------------------- | --------------- | -------------------------
298 json.exception.type_error.301 | cannot create object from initializer list | To 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.
299 json.exception.type_error.302 | type must be object, but is array | During 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.
300 json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t &.
301 json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
302 json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
303 json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
304 json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
305 json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types.
306 json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
307 json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
308 json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types.
309 json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
310 json.exception.type_error.313 | invalid value to unflatten | The @ref 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.
311 json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
312 json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive.
313 json.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref 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. |
314 json.exception.type_error.317 | JSON value cannot be serialized to requested format | The 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) |
315 
316 @liveexample{The following code shows how a `type_error` exception can be
317 caught.,type_error}
318 
319 @sa - @ref exception for the base class of the library exceptions
320 @sa - @ref parse_error for exceptions indicating a parse error
321 @sa - @ref invalid_iterator for exceptions indicating errors with iterators
322 @sa - @ref out_of_range for exceptions indicating access out of the defined range
323 @sa - @ref other_error for exceptions indicating other library errors
324 
325 @since version 3.0.0
326 */
327 class type_error : public exception
328 {
329   public:
330     template<typename BasicJsonType>
create(int id_,const std::string & what_arg,const BasicJsonType & context)331     static type_error create(int id_, const std::string& what_arg, const BasicJsonType& context)
332     {
333         std::string w = exception::name("type_error", id_) + exception::diagnostics(context) + what_arg;
334         return type_error(id_, w.c_str());
335     }
336 
337   private:
338     JSON_HEDLEY_NON_NULL(3)
type_error(int id_,const char * what_arg)339     type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
340 };
341 
342 /*!
343 @brief exception indicating access out of the defined range
344 
345 This exception is thrown in case a library function is called on an input
346 parameter that exceeds the expected range, for instance in case of array
347 indices or nonexisting object keys.
348 
349 Exceptions have ids 4xx.
350 
351 name / id                       | example message | description
352 ------------------------------- | --------------- | -------------------------
353 json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1.
354 json.exception.out_of_range.402 | array index '-' (3) is out of range | The 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.
355 json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
356 json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
357 json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value.
358 json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF.
359 json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. (until version 3.8.0) |
360 json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. |
361 json.exception.out_of_range.409 | BSON key cannot contain code point U+0000 (at byte 2) | Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string |
362 
363 @liveexample{The following code shows how an `out_of_range` exception can be
364 caught.,out_of_range}
365 
366 @sa - @ref exception for the base class of the library exceptions
367 @sa - @ref parse_error for exceptions indicating a parse error
368 @sa - @ref invalid_iterator for exceptions indicating errors with iterators
369 @sa - @ref type_error for exceptions indicating executing a member function with
370                     a wrong type
371 @sa - @ref other_error for exceptions indicating other library errors
372 
373 @since version 3.0.0
374 */
375 class out_of_range : public exception
376 {
377   public:
378     template<typename BasicJsonType>
create(int id_,const std::string & what_arg,const BasicJsonType & context)379     static out_of_range create(int id_, const std::string& what_arg, const BasicJsonType& context)
380     {
381         std::string w = exception::name("out_of_range", id_) + exception::diagnostics(context) + what_arg;
382         return out_of_range(id_, w.c_str());
383     }
384 
385   private:
386     JSON_HEDLEY_NON_NULL(3)
out_of_range(int id_,const char * what_arg)387     out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
388 };
389 
390 /*!
391 @brief exception indicating other library errors
392 
393 This exception is thrown in case of errors that cannot be classified with the
394 other exception types.
395 
396 Exceptions have ids 5xx.
397 
398 name / id                      | example message | description
399 ------------------------------ | --------------- | -------------------------
400 json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
401 
402 @sa - @ref exception for the base class of the library exceptions
403 @sa - @ref parse_error for exceptions indicating a parse error
404 @sa - @ref invalid_iterator for exceptions indicating errors with iterators
405 @sa - @ref type_error for exceptions indicating executing a member function with
406                     a wrong type
407 @sa - @ref out_of_range for exceptions indicating access out of the defined range
408 
409 @liveexample{The following code shows how an `other_error` exception can be
410 caught.,other_error}
411 
412 @since version 3.0.0
413 */
414 class other_error : public exception
415 {
416   public:
417     template<typename BasicJsonType>
create(int id_,const std::string & what_arg,const BasicJsonType & context)418     static other_error create(int id_, const std::string& what_arg, const BasicJsonType& context)
419     {
420         std::string w = exception::name("other_error", id_) + exception::diagnostics(context) + what_arg;
421         return other_error(id_, w.c_str());
422     }
423 
424   private:
425     JSON_HEDLEY_NON_NULL(3)
other_error(int id_,const char * what_arg)426     other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
427 };
428 }  // namespace detail
429 }  // namespace nlohmann
430