Handling Schema Decoding Failures with Fallback to Undefined

this feels like a dumb question, but how would you write a schema such that if part of decoding fails, it falls back to null? For example:

const S = Schema.Struct({
  myUrl: Schema.URL,
})
// 👇 I want this to be null 
const value = Schema.decodeSync(S)({myUrl: "not a url"})


I know that I can use Schema.transform to catch a failure manually, but is there a way to make this pattern more generic where it can attempt any transform and catch it if it fails:

const SafeURL = Schema.transform(
  Schema.NullOr(Schema.encodedSchema(Schema.URL)),
  Schema.NullOr(Schema.typeSchema(Schema.URL)), 
  {
    strict: true,
    decode: (input, options) => {
      if (!input) return null
      try {
        return new URL(input)
      } catch (e) {
        return null
      }
    },
    encode: (value) => {
      if (value === null) {
        return null
      }
      return value.toString()
    }
  }
).pipe(Schema.asSchema)


So that I could call MakeSafe(MySchema) and it would make the whole value nullable when a transformation fails? I specifically do not want to do this at the Schema.decode call site or level because this struct is actually deeply nested inside another one, and I only want the one value to fail with null if it doesn't transform successfully.

https://effect.website/play/#afaabcd87587
Was this page helpful?