Skip to content

readGeneric returns TypeMismatch instead of ErrorAtProperty for missing properties #8

@dkoontz

Description

@dkoontz

I'm not sure if this is intentional but after I switch from implementing a custom read to using the readGeneric my error message for missing properties changed from

Left {
  value0:
   ErrorAtProperty {
     value0: 'y',
     value1: TypeMismatch { value0: 'Number', value1: 'Undefined' } } }

to

Left {
  value0: TypeMismatch { value0: 'Number', value1: 'Undefined' } }

I don't know if the ErrorAtProperty value is created when using readProp as I see readGeneric uses specific readXYZ functions based on the spine data. In any event, this makes parsing JS data significantly harder as you don't know where the error occurred and you're told it's a type mismatch when it's really a missing property.

Here is the test case

module Test where

import Prelude
import Data.Foreign
import Data.Foreign.Class
import Data.Foreign.Generic
import Data.Generic

parseOptions :: Options
parseOptions = defaultOptions { unwrapNewtypes = true }

data Vector2 = Vector2 { x :: Number, y :: Number }

derive instance genericVector :: Generic Vector2

-- This version produces a TypeMismatch error when one of the fields is missing
instance vector2IsForeign :: IsForeign Vector2 where
  read = readGeneric parseOptions

-- You can test this version to see a ErrorAtProperty error
-- instance vector2IsForeign :: IsForeign Vector2 where
--   read value = do
--     x <- readProp "x" value
--     y <- readProp "y" value
--     return $ Vector2 { x, y }

parseVector2 :: Foreign -> F Vector2
parseVector2 = read
"use strict";

var Test = require('Test');

console.log(Test.parseVector2({x: 0, y: 0})); // should parse fine and give Right value
console.log(Test.parseVector2({x: 0})); // should error with missing y
console.log(Test.parseVector2({y: 0})); // should error with missing x

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions