Clojure:如何在异常后恢复 REPL?

Clojure: How to restore REPL after exception?

当您 restart/reload 您的应用程序使用挂载后出现错误时,正确的工作流程是什么?

一个例子:

user> (restart)
#error {
 :cause "Unable to resolve symbol: account-database in this context"
 :via
 [{:type clojure.lang.Compiler$CompilerException
   :message "Syntax error compiling at (app/model/session.clj:55:39)."
   :data #:clojure.error{:phase :compile-syntax-check, :line 55, :column 39, :source "app/model/session.clj"}
   :at [clojure.lang.Compiler analyze "Compiler.java" 6808]}
  {:type java.lang.RuntimeException
   :message "Unable to resolve symbol: account-database in this context"
   :at [clojure.lang.Util runtimeException "Util.java" 221]}]
 :trace
 [[clojure.lang.Util runtimeException "Util.java" 221]
Reloadable Clojure REPL
user> (restart)
Syntax error compiling at (*cider-repl Projects/pollcro:localhost:43993(clj)*:597:7).
Unable to resolve symbol: restart in this context
user> (start)
Syntax error compiling at (*cider-repl Projects/pollcro:localhost:43993(clj)*:600:7).
Unable to resolve symbol: start in this context

修复错误后,由于以下错误,我无法(重新启动)此回复:

Unable to resolve symbol: restart in this context

总是这样还是我的 REPL 工作流程有问题?

作为一种变通方法,我用 cider 退出了 REPL 会话并重新启动它,但这很烦人。

修复错误后似乎可以使用mount/start:

user> (mount/start)
{:started
 ["#'app.server-components.config/config"
  "#'app.model.database/pool"
  "#'app.model.mock-database/conn"]}

但它完全失去了我的用户命名空间范围,REPL 看不到它的任何方法 + 由于以下错误,我无法将用户命名空间发送到 repl:

Syntax error compiling at (app/server_components/pathom.clj:1:1).
namespace 'app.model.session' not found
("src/main" "src/dev" "src/test")#function[expound.alpha/printer]nil#'user/start#'user/stop#'user/restartnil


这就是我的 user namespace 的样子:

(ns user
  (:require
    [clojure.tools.namespace.repl :as tools-ns :refer [set-refresh-dirs]]
    [expound.alpha :as expound]
    [clojure.spec.alpha :as s]
    [mount.core :as mount]
    ;; this is the top-level dependent component...mount will find the rest via ns requires
    [app.server-components.http-server :refer [http-server]]))

;; ==================== SERVER ====================
(set-refresh-dirs "src/main" "src/dev" "src/test")
;; Change the default output of spec to be more readable
(alter-var-root #'s/*explain-out* (constantly expound/printer))

(defn start
  "Start the web server"
  [] (mount/start))

(defn stop
  "Stop the web server"
  [] (mount/stop))

(defn restart
  "Stop, reload code, and restart the server. If there is a compile error, use:

  (tools-ns/refresh)

  to recompile, and then use `start` once things are good."
  []
  (stop)
  (tools-ns/refresh :after 'user/start))

以下是在出现错误时似乎有效的解决方法:

  1. 固定文件的内容需要发送到REPL
  2. 切换回 user 命名空间
  3. 将您的 user 命名空间的内容发送到 REPL
  4. 没有 4 - 您刚刚取回了 REPL。

此时您可以使用常规 (start)(stop)(restart)