Error Handling
Error Handling
Dynamic entities throw exceptions in the case of an error, rather than returning a %StatusOpens in a new tab value. In the following example, the thrown exception includes enough information to conclude that the second character in the method argument is invalid (property should be enclosed in quotes):
set string = "{property:1,}"
<THROW>%FromJSON+37^%Library.DynamicAbstractObject.1 *%Exception.General Parsing error 3 Line 1 Offset 2
When dealing with dynamic data, it is always wise to assume that some data will not fit your expectations. Any code that makes use of dynamic objects should be surrounded with a TRY-CATCH block at some level (see “The TRY-CATCH Mechanism” in Using ObjectScript) so your code can provide error handling. For example, wrapping this exception in a try-catch allows the exception data to be accessed via the standard %Exception.AbstractExceptionOpens in a new tab object:
try {
set string = "{property:1,}"
set json = ##class(%DynamicObject).%FromJSON(string)
} catch ex {
write "Trapped error ", ex.Code_": "_ex.Name_", "_ex.Location, !
}
Trapped error 3: Parsing error, Line 1 Offset 2
The following table may help you deduce more about where an exception originated.
Error constant | code | Name (explanation) |
---|---|---|
JSON_ERROR_OKAY | 1 | Compilation okay |
JSON_ERROR_NOSTRING | 2 | Cannot get string from source (source wasn't a string) |
JSON_ERROR_PARSEFAIL | 3 | Parsing error (while parsing JSON string) |
JSON_ERROR_INTERNAL_ERROR | 4 | Internal error |
JSON_ERROR_NO_MEMORY | 5 | Insufficient memory (memory allocation failure) |
JSON_ERROR_INVALID_HEX | 6 | Escaped hex sequence invalid (in \uXXXX string) |
JSON_ERROR_OVERFLOW_HEX | 7 | Escaped hex sequence too large (too big for 8-bit systems) |
JSON_ERROR_INVALID_ESCAPE | 8 | Escape sequence invalid |
JSON_ERROR_MAX_NUMERIC | 9 | Numeric exceeds %d characters (numeric is too large) |
JSON_ERROR_READ_ERROR | 10 | READ error while reading input stream |
JSON_ERROR_MAX_DEPTH | 11 | Depth exceeds %d levels |
JSON_ERROR_UNEXPECTED_EOF | 12 | Premature end of data |
JSON_ERROR_DUPLICATE_KEY | 13 | Duplicate key |
JSON_ERROR_IRIS_KERNEL | 14 | System error %s |
JSON_ERROR_METADATA | 15 | Output exceeded maximum size of %d (metadata missing or illegal) |
JSON_ERROR_CORRUPT_STRUCTURE | 16 | Corrupt internal array structure |
JSON_ERROR_INVALID_ZU_ARGS | 17 | Array metadata missing or illegal (invalid arguments passed to $zu(210)) |
JSON_ERROR_MAXSIZE | 18 | Output variable exceeded maximum size |