Elixir中错误处理的最佳方法是什么

Smartechno

我正在使用简单的凤凰e剂应用程序。在这个应用程序中,我试图公开一个REST API来保存和检索数据。

就我而言,如果主键(电子邮件地址)重复,则我的应用程序将引发错误。我需要知道处理此错误的最佳方法。尝试捕获或任何其他更好的解决方案。

这是我的数据保存方法

def post(conn, %{"stooge" => stooge, "name" => name, "email" => email , "password" => password})do
    respond = Repo.insert!(%ApiDb.User{name: name, email: email, stooge: stooge, password: password})
    json conn, respond
  end

样本有效载荷

{
    "stooge": "moe",
    "name": "Joe",
    "email": "[email protected]",
    "password":"asdasd"
}

型号/user.ex

defmodule ApiDb.User do
  use ApiDb.Web, :model
  schema "users" do
    field :password, :string
    field :name, :string
    field :email, :string
    field :stooge, :string
    timestamps()
  end

   @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:name, :email, :password, :stooge])
    |> validate_required([:name, :email, :password])
    |> validate_format(:email, ~r/@/)
  end
end

错误 在此处输入图片说明

我尝试了try-catch块,但是没有运气

try do
    respond = Repo.insert!(%ApiDb.User{name: name, email: email, stooge: stooge, password: password})
    json conn, respond
rescue 
  e in Ecto.ConstraintError -> IO.puts("An error occurred: ")
end
Smartechno

找到了很好的简单方法

 def post(conn, %{"stooge" => stooge, "name" => name, "email" => email , "password" => password})do
    try do
        respond = Repo.insert!(%ApiDb.User{name: name, email: email, stooge: stooge, password: password})
        json conn, respond
    rescue 
      e in Ecto.ConstraintError ->  json conn, (%{"status" => false, "message" => e.message})
    end
  end

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在C ++中重现“ cold / never_inline”错误处理技术的最佳方法是什么?

在angular.js应用程序中全局进行错误处理的最佳方法是什么?

烧瓶错误处理的最佳实践是什么?

Spring Data JPA错误处理的最佳实践是什么

在 useMutation 钩子中处理错误的最佳方法是什么

在React Redux中处理提取错误的最佳方法是什么?

在Combine中处理错误的最佳方法是什么?

使用Rails中的模块执行错误处理的最佳方法?

在Perl中写入文件时测试错误处理的最简单方法是什么?

处理 RxSwift 重试和错误处理的最佳实践是什么

时钟类错误处理的最佳方法?

使用Catalyst :: Controller :: REST进行错误处理的最佳实践是什么

nestjs错误处理方法是什么(业务逻辑错误与http错误)?

处理浮点错误的最佳方法是什么?

在vuejs中处理Http Exception错误消息的最佳方法是什么?

在 VBA 中处理属性内部数据输入错误的最佳方法是什么

对于客户端和服务器错误,无状态React表单的最佳错误处理流程是什么?

处理在R中连接的多个表的最佳方法是什么?

在美丽的汤蟒中处理无的最佳方法是什么

在调度程序中处理AEM缓存的最佳方法是什么?

在 ef core 2 中处理连接的最佳方法是什么

在Spring Boot中处理异常的最佳方法是什么?

在雄辩模型中处理ACL的最佳模式或方法是什么?

在Flutter中处理屏幕尺寸的最佳方法是什么?

在Rails表单对象中处理日期的最佳方法是什么

在NodeJS中处理数据的最佳方法是什么?

在NodeJS中处理大块文本的最佳方法是什么?

处理红宝石中嵌套条件的最佳方法是什么?

在 BluePrism 中处理动态 Iframe 值的最佳方法是什么