榆树:从列表中获取第一条错误消息

elm: get first error message from a list

赠送模特(与相关):

type alias ValidationResult =
    { parameter : String
    , errorMessage : String
    }


type alias ErrorResponse =
    { validationErrors : List ValidationResult }


decodeValidationResults : Decoder ValidationResult
decodeValidationResults =
  map2 ValidationResult
    (field "Parameter" string)
    (field "ErrorMessage" string)

decodeErrorResponse : Decoder ErrorResponse
decodeErrorResponse =
    map ErrorResponse
        (field "ValidationErrors" (list decodeValidationResults))

我想创建一个函数,returns 来自 ErrorResponse 的第一个错误消息。这是我尝试过的:

firstErrorMessage : Decoder CardEngineErrorResponse -> String
firstErrorMessage decoder response =
    case List.head response.validationErrors of
        Just something ->
            something.errorMessage

        Nothing ->
            toString ""

但我收到错误消息:

The definition of `firstErrorMessage` does not match its type annotation.

The type annotation for `firstErrorMessage` says it always returns:
 
     String
 
 But the returned value (shown above) is a:
 
     { b | validationErrors : List { a | errorMessage : String } } -> String
 
 Hint: It looks like a function needs 1 more argument.

你们有谁知道我做错了什么吗?

如果您只是想从 ErrorResponse 值中获取第一条错误消息,则不需要引用 Decoder:

firstErrorMessage : ErrorResponse -> String
firstErrorMessage response =
    case List.head response.validationErrors of
        Just something ->
            something.errorMessage

        Nothing ->
            ""

或者更简洁地说:

firstErrorMessage : ErrorResponse -> String
firstErrorMessage response =
    List.head response.validationErrors
        |> Maybe.map .errorMessage
        |> Maybe.withDefault ""

如果您尝试在解码器的上下文中执行所有操作,则可以使用 Json.Decode.map:

firstErrorMessageDecoder : Decoder String
firstErrorMessageDecoder =
    decodeErrorResponse
        |> map firstErrorMessage

再注意一点:当某件事有失败的可能性时,通常最好保留Maybe的概念。您可以通过返回 Maybe String:

来构建更强大的 API,而不是调用者必须知道的默认空字符串
firstErrorMessage : ErrorResponse -> Maybe String
firstErrorMessage response =
    List.head response.validationErrors
        |> Maybe.map .errorMessage