大多数EOF会产生有用的错误信息,如JSON错误(字符串内的文件末尾)
。但对象和数组读取器不处理EOF并抛出不友好的异常。
(clojure.data.json/read-str "{")
由于read-key
中的以下行抛出错误Value out of range for char: -1
。
(throw (Exception. (str "JSON error (non-string key in object), found
" (char c) ", expected
\"")))
(char c)
抛出异常,因为c是-1。
这是通过在read-key
中处理-1情况来修复的。
(defn- read-key [^PushbackReader stream]
(let [c (int (next-token stream))]
(if (= c (codepoint \"))
(let [key (read-quoted-string stream)]
(if (= (codepoint \:) (int (next-token stream)))
key
(throw (Exception. "JSON error (missing `:` in object)"))))
(codepoint-case c
\} nil
-1 (throw (Exception. "JSON error (end-of-file inside object)"))
(throw (Exception. (str "JSON error (non-string key in object), found `" (char c) "`, expected `\"`")))))))
(clojure.data.json/read-str "{\"\":\"\"")
给出错误的错误信息:JSON错误(对象中缺少条目)
。
这是通过在read-object
中处理EOF来修复的。
(codepoint-case (int (next-token stream))
\, (recur r)
\} (persistent! r)
-1 (throw (Exception. "JSON error (end-of-file inside object)"))
(throw (Exception. "JSON error (missing entry in object)"))))
(clojure.data.json/read-str "[")
抛出错误JSON错误(意外的字符):
(意外字符是(char 65535))。这是因为在read-array
中,-1被推回流,并且-1被推为65535。
修复是处理read-array
中的EOF。
(defn- read-array [^PushbackReader stream options]
;; Expects to be called with the head of the stream AFTER the
;; opening bracket.
;; Only handles array value.
(let [c (int (next-token stream))]
(codepoint-case c
\] []
\, (throw (invalid-array-exception))
-1 (throw (Exception. "JSON error (end-of-file inside array)"))
(do (.unread stream c)
(read-array* stream options)))))