2016-12-13 78 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

如果你永遠不會來皇馬,請告訴我,因爲我擁有你的箱子啤酒 ;) –