2

以前,我会with在 Elixir Plug 服务器中使用块来解析请求中的参数,并在失败时返回理智的响应。但是,这似乎不再起作用(Elixir 1.11)。谁能指出发生了什么?

Plug这是一个将显示问题的极简服务器

defmodule MatchTest.Router do
  use Plug.Router

  plug(:match)
  plug(:dispatch)

  get "/" do
    other_with =
      with {:ok, _} <- Map.fetch(%{}, "test") do
        :ok
      else
        :error -> :error
      end

    with conn <- Plug.Conn.fetch_query_params(conn),
         {:ok, a} = Map.fetch(conn.query_params, "a") do
      Plug.Conn.send_resp(conn, 200, "a = #{a}; other_with = #{other_with}")
    else
      :error -> Plug.Conn.send_resp(conn, 400, "Incorrect Parameters")
    end
  end

  match _ do
    Plug.Conn.send_resp(conn, 404, "Not Found")
  end
end

defmodule MatchTest do
  use Application

  def start(_type, _args) do
    Supervisor.start_link(
      [{Plug.Cowboy, scheme: :http, plug: MatchTest.Router, options: [port: 4000]}],
      strategy: :one_for_one,
      name: RateLimitedServer.Supervisor
    )
  end
end

正如预期的那样,当我a在 GET 请求中包含参数时,一切正常:

ddrexler@Drexbook-Pro:temp|$ http -v get localhost:4000/ a=="test"
GET /?a=test HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Host: localhost:4000
User-Agent: HTTPie/2.3.0



HTTP/1.1 200 OK
cache-control: max-age=0, private, must-revalidate
content-length: 28
date: Mon, 15 Feb 2021 22:40:14 GMT
server: Cowboy

a = test; other_with = error

特别是,第一个with子句按预期工作,当我们尝试Map.fetch()从空映射中跳转时,它会跳转到else子句中(您可以看到这是因为字符串“other_with = error”)。

但是,当我尝试排除参数时,我得到 500:

ddrexler@Drexbook-Pro:~|$ http -v get localhost:4000/
GET / HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Host: localhost:4000
User-Agent: HTTPie/2.3.0



HTTP/1.1 500 Internal Server Error
content-length: 0

服务器得到一个未捕获的 MatchError:

ddrexler@Drexbook-Pro:match_test|$ mix run --no-halt
Compiling 1 file (.ex)
warning: "else" clauses will never match because all patterns in "with" will always match
  lib/match_test.ex:15


14:40:16.341 [error] #PID<0.350.0> running MatchTest.Router (connection #PID<0.349.0>, stream id 1) terminated
Server: localhost:4000 (http)
Request: GET /
** (exit) an exception was raised:
    ** (MatchError) no match of right hand side value: :error
        (match_test 0.1.0) lib/match_test.ex:16: anonymous fn/2 in MatchTest.Router.do_match/4
        (match_test 0.1.0) lib/plug/router.ex:284: MatchTest.Router.dispatch/2
        (match_test 0.1.0) lib/match_test.ex:1: MatchTest.Router.plug_builder_call/2
        (plug_cowboy 2.4.1) lib/plug/cowboy/handler.ex:12: Plug.Cowboy.Handler.init/2
        (cowboy 2.8.0) /Users/ddrexler/src/elixir/match_test/deps/cowboy/src/cowboy_handler.erl:37: :cowboy_handler.execute/2
        (cowboy 2.8.0) /Users/ddrexler/src/elixir/match_test/deps/cowboy/src/cowboy_stream_h.erl:300: :cowboy_stream_h.execute/3
        (cowboy 2.8.0) /Users/ddrexler/src/elixir/match_test/deps/cowboy/src/cowboy_stream_h.erl:291: :cowboy_stream_h.request_process/3
        (stdlib 3.13.2) proc_lib.erl:226: :proc_lib.init_p_do_apply/3

另请注意警告"else" clauses will never match because all patterns in "with" will always match- 显然是不真实的!有一种情况是它们不匹配,因为我得到了一个 MatchError。该else块包括一个:error选项,它应该捕获这个结果!

4

1 回答 1

3

您可能已经从@sbacarob 的评论中解决了这个问题。

你的错误来了,因为当没有aparam:{:ok, a} = Map.fetch(conn.query_params, "a")被评估为{:ok, a} = :error并且引发MatchError.

为避免MatchError您需要使用特殊的with特定运算符<-。你可以把它想象成一个“软匹配”运算符(其中=是“硬匹配”)。软匹配让匹配失败(在 a 中with)并下降到 else/end,而硬匹配将 raise MatchError

于 2021-02-16T00:00:31.167 回答