2016-12-13 84 views
0

给模型(相关this)获得第一个错误信息:榆树:从列表

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)) 

我想创建一个从错误响应返回福斯特错误消息的功能。这里是我已经试过:

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. 

你们有任何想法,我做错了什么?

回答

2

如果你只是想从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的概念。相反,默认为哪些呼叫者必须了解空字符串,你可以通过返回建立一个更强大的API一个Maybe String

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

如果你永远不会来皇马,请告诉我,因为我拥有你的箱子啤酒 ;) –