2017-06-06 68 views
1

我曾經在一個控制器下面的動作在我的鳳凰應用程序返回JSON:救援Phoenix.MissingParamError和用戶

 plug :scrub_params, "account" 
     plug :scrub_params, "studio" 

     def create(conn, %{"account" => account_params, "studio" => studio_params}) do 
     end 

當有人不發送正確PARAMS應用程序將返回Phoenix.MissingParamError錯誤。我該如何解救它並在json中向用戶返回好消息?

+0

在Phoenix 1.3中,您可以使用action_fallback並將錯誤處理移動到一個不同的錯誤控制器。 – PatNowak

+0

這個'Phoenix.MissingParamError'正在拋出我的'scrub_params'嗎?在這種情況下,添加另一個子句(如現在的頂級答案)將不起作用。 – Dogbert

回答

2

您可以創建另一個函數頭來處理這種情況。像這樣的東西,也許

def create(conn, %{"account" => account_params, "studio" => studio_params}) do 
    # handle request 
end 

def create(conn, params) do 
    # handle missing param 
end 
+0

我正在考慮這個問題,但是我需要重複一遍這個不好的行爲...... –

1

也許你可以使用Plug.ErrorHandler。像這樣的東西。

defmodule AppRouter do 
    use Plug.Router 
    use Plug.ErrorHandler 

    ... 

    def handle_errors(conn, %{kind: _kind, reason: _reason, stack: _stack}) do 
    send_resp(conn, conn.status, "Something went wrong") 
    end 
end