管道和错误处理

时间:2017-03-28 17:24:13

标签: error-handling exception-handling pipe elixir

假设您有以下功能:

Dim pt As PivotTable
Dim pi As PivotItem
Dim strField As String

strField = "Cslts"

Application.ScreenUpdating = False

If Target.Address = Range("H1").Address Then

    For Each pt In ActiveSheet.PivotTables

        With pt.PageFields(strField)

            For Each pi In .PivotItems

                If pi.Value = Target.Value Then

                    Dim bUserNameFound
                    bUserNameFound = True

                    Exit For

                End If

            Next pi

            If bUserNameFound Then
                .CurrentPage = Target.Value
            Else
                .CurrentPage = "(blank)"
            End If

        End With

    Next pt

End If

现在说def get_city_temp(city_id) do 'blahblahcityforcastfortoday.com/request/#{city_id}' |> HTTPoison.get |> parse_body |> get_forecast |> get_temp end 失败了,所以回复是:

GET

{:ok, %HTTPoison.Response{status_code: 400, ...}} 期待一个结构良好的身体,因此会抱怨传递给它的结构,或丢失的密钥等。处理这样的错误的最佳方法是什么?在其他语言中,我只是在get_forecast try中包装所有函数调用,并返回带有成功报告的元组。在这种情况下,我不确定如何构建我的代码以最好地报告错误 给用户。

1 个答案:

答案 0 :(得分:5)

这正是with/1宏的用途。假设parse_body和其他函数在成功时返回{:ok, _}而在失败时返回{:error, _},您可以这样做:

with {:ok, response} <- HTTPoison.get(...),
     {:ok, parsed} <- parse_body(response),
     {:ok, forecast} <- get_forecast(parsed),
     {:ok, temp} <- get_temp(forecast), do: {:ok, temp}

如果任何模式匹配失败,则整个事件返回该值。例如,如果get_forecast在所有先前的函数返回{:error, :foo}后返回{:ok, _},则with将返回{:error, :foo}

相关问题