Unexpected operator ->. If you want to define multiple clauses, the first expression must use ->. Syntax error before: '->'

hello, the problem is that the create function in the controller is giving me problems:

unexpected operator ->. If you want to define multiple clauses, the first expression must use ->. Syntax error before: '->'
    (elixir 1.10.3) lib/kernel/parallel_compiler.ex:304: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/7

this is my controller:

def create(conn, params) do
    with {:ok, request} <- handle.map(params) do
      Project.ProjectBuilderSupervisor.build_receipt(request)

      conn
      |> put_status(:ok)
      |> render("ok.json")
    
      error ->
        conn |> put_status(:bad_request) |> put_view(ProjectWeb.ErrorView) |> render(:"400")
    end
  end

does anyone have any idea how to solve, please?

add else before error ->

adding the else is giving this error

else
 error ->
        conn |> put_status(:bad_request) |> put_view(ProjectWeb.ErrorView) |> render(:"400")
    end

**with contains only one ← clause and an else branch, use a case **
┃ instead

You are using with with one condition only…

It says to use case instead.

with is used for pipelines of more than one condition, which could break.

1 Like

The error is informing you that with is not the right solution: since you have only a single clause, and an else branch, your code is better written using a case:

def create(conn, params) do
  case handle.map(params) do
    {:ok, request} ->
      Project.ProjectBuilderSupervisor.build_receipt(request)

      conn
      |> put_status(:ok)
      |> render("ok.json")
    
    _ ->
      conn |> put_status(:bad_request) |> put_view(ProjectWeb.ErrorView) |> render(:"400")
  end
end

As @kokolegorille said, with is used in situations when you have a chain of several clauses, each of which could give an error, and you want to break out from the chain on the first error:

with {:ok, foo} <- Map.fetch(options, :foo),
     {:ok, bar} <- Map.fetch(options, :bar) do
  # ...do something with foo and bar
else
  :error ->
    # ...handle error
end

In your case, with is not necessary, and ends up being more cumbersome. Therefore the message tells you to use case instead.

5 Likes

Note that this is an issue raised by Credo. The code is legal Elixir.

4 Likes

thank u

1 Like

Welcome :slight_smile: