csvhelperのエラー処理


Summary

csvhelperにおけるエラー処理

script

#r "nuget: csvhelper"

open System.Globalization
open System.IO
open CsvHelper
open CsvHelper.Configuration


[<CLIMutable>]
type public Csv =
  {
    name : string
    price : int
    color : string
    memo : string
  }


[<Sealed>]
type public CsvMap () as this =
  inherit ClassMap<Csv>()
  do
    this.Map(fun x -> x.name).Index(0) |> ignore
    this.Map(fun x -> x.price).Index(1) |> ignore
    this.Map(fun x -> x.color).Index(2) |> ignore
    this.Map(fun x -> x.memo).Index(3) |> ignore


let public csvRead  (streamReader:StreamReader)  =

  let csvConfig : CsvConfiguration  =
    CsvConfiguration(CultureInfo.CurrentCulture)
    |> fun x ->
      x.Delimiter <- ","
      x.HasHeaderRecord <- true
      x.DetectColumnCountChanges <- true
      x

  use csv = new CsvReader(streamReader , csvConfig )
  csv.Context.RegisterClassMap<CsvMap>() |> ignore

  let mutable flg = true
  while flg do
    try
      flg <- (csv.Read())
      if flg
      then csv.GetRecord<Csv>() |> printfn "%A"
    with
      | :? BadDataException ->
        printfn "bad data exception!"
      | :? TypeConversion.TypeConverterException ->
        printfn "type conversion exception!"
      | _ ->
        printfn "others exeption!"


new StreamReader( "./fruits.csv"  )
|> csvRead

Csv1

name,price,color,memo
apple,300,red,solid sweet!
banana,1,980,yellow,great sweet!
cherry,520,black,very delicious!

error

{ name = "apple"
  price = 300
  color = "red"
  memo = "solid sweet!" }
bad data exception!
{ name = "cherry"
  price = 520
  color = "black"
  memo = "very delicious!" }

csv2

name,price,color,memo
apple,300,red,solid sweet!
banana,aaa,yellow,great sweet!
cherry,520,black,very delicious!

error

{ name = "apple"
  price = 300
  color = "red"
  memo = "solid sweet!" }
type conversion exception!  
{ name = "cherry"
  price = 520
  color = "black"
  memo = "very delicious!" }

現場からは以上です