【问题标题】:Exceptions: Unbound cannot be cast to clojure.lang.Named,compiling例外:未绑定不能转换为 clojure.lang.Named,正在编译
【发布时间】:2015-06-11 19:57:52
【问题描述】:

我正在尝试使用 clj-http/client 来检索网页。看起来它有点工作,但有时我会收到这种异常

线程“main”java.lang.ClassCastException 中的异常:clojure.lang.Var$Unbound 无法转换为 clojure.lang.Named,编译:(/tmp/form-init8570082100332402765.clj:1:72)

这是一个简单的函数,它从数据库(来自 jdbc/query :row-fn)检索 url,请求 url 的内容并将其写入数据库。代理数据是随机的,仅供参考。

(defn get-source
  "get content of an url"
  [row]
  (def my-proxy "72.159.148.20")
  (def my-port 10000)
  (def my-url (:url row))
  (def h {"User-Agent" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/34.0"})
  (try
  (def my-body (:body (client/get my-url {:proxy-host my-proxy :proxy-port my-port :follow-redirects false :headers h  :conn-timeout 100000})))
  (catch clojure.lang.ExceptionInfo e
    (prn "caught" e))
    )
  (write-data-to-db my-url my-body))

行的值来自简单的数据库查询:

(defn -main
  "I don't do a whole lot ... yet."
  [& args]
  (def db-spec
    {
 :subprotocol "mysql"
 :subname "//localhost:3306/a"
 :user "user"
 :password "pass"})
 ((jdbc/query db-spec ["SELECT url FROM main where html is null and url is not null limit 2"] :row-fn get-source)))

感谢您的健康批评,我已将我的示例修正为更正确。

    (defn get-source
      "get list of urls to grab in"
      [row]
      (let [proxy "107.161.31.220" port 8080 url (:url row) 
h {"User-Agent" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/34.0"}]
      (:status (client/get url {:proxy-host proxy :proxy-port port :follow-redirects false :headers h  :conn-timeout 100000}))))

我希望这样会更好,我再也无法得到那个异常,所以它可能被埋在我最初带来的那个烂摊子里。

【问题讨论】:

  • 没有缩进很难阅读代码。 PS:了解let
  • 我在可以使用let 的地方使用def,还有什么地方可以帮助缩进?在我的屏幕上,它看起来很有意境,几乎和 clj-http 示例中的一样好。
  • 行的数据结构和值是什么?
  • 我刚刚添加到主帖,所以它就像{:url "http://something"}
  • "我在可以使用 let 的地方使用了 def" 你知道 def 只创建可变的全局容器吗?这与 Scheme 中的 def 不同。如果你曾经使用过线程,你的代码将会做出不可预测的错误事情。

标签: exception-handling clojure


【解决方案1】:

我认为在 Clojure 中定义函数或“块”中的某些内容不是惯用的(或者它只是不是声明性的)。 Def 声明了全局变量。

来自http://clojure.org/special_forms:

(定义符号初始化?)

使用符号名称和当前命名空间值的命名空间创建和实习或定位一个全局变量。 <...> def 产生 var 本身(不是它的值)。

我猜你必须将 (write-data-to-db) 放入 try-block 并使用 let 而不是 def。现在你正在尝试访问可能失败的东西的价值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 2015-02-23
    相关资源
    最近更新 更多