Suggestions for Improving Error Handling in User Input Validation
import { Either as E, Match as M, ParseResult, Schema as S } from 'effect'
export const PrimaryKeyIndex = S.NonNegative.pipe(S.brand('PrimaryKeyIndex'))
export class AccountCreate extends S.Class<AccountCreate>('AccountCreate')({
name: S.NonEmptyString.pipe(S.minLength(4), S.maxLength(12)),
state: S.Literal('AAAA', 'BBBB', 'CCCC'),
apiKey: S.NonEmptyString
}) {
static readonly decode = S.decodeEither(this, {
exact: true,
onExcessProperty: 'error'
})
static readonly encode = S.decodeEither(this, {
exact: true,
onExcessProperty: 'error'
})
}
export class AccountModel extends AccountCreate.extend<AccountModel>(
'AccountModel'
)({
uid: PrimaryKeyIndex
}) {
static readonly decode = S.decodeEither(this, {
exact: true,
onExcessProperty: 'error'
})
static readonly encode = S.decodeEither(this, {
exact: true,
onExcessProperty: 'error'
})
}
const s = AccountCreate.decode({
name: '1234',
state: 'AAAA',
apiKey: 1234
})
if (E.isLeft(s)) {
const { path } = ParseResult.ArrayFormatter.formatErrorSync(s.left)[0]!
const cause = M.value(path).pipe(
M.when(['name'], () => 'name'),
M.when(['state'], () => 'state'),
M.when(['apiKey'], () => 'apiKey')
)
console.log(`invalid ${cause.value.right}`)
}import { Either as E, Match as M, ParseResult, Schema as S } from 'effect'
export const PrimaryKeyIndex = S.NonNegative.pipe(S.brand('PrimaryKeyIndex'))
export class AccountCreate extends S.Class<AccountCreate>('AccountCreate')({
name: S.NonEmptyString.pipe(S.minLength(4), S.maxLength(12)),
state: S.Literal('AAAA', 'BBBB', 'CCCC'),
apiKey: S.NonEmptyString
}) {
static readonly decode = S.decodeEither(this, {
exact: true,
onExcessProperty: 'error'
})
static readonly encode = S.decodeEither(this, {
exact: true,
onExcessProperty: 'error'
})
}
export class AccountModel extends AccountCreate.extend<AccountModel>(
'AccountModel'
)({
uid: PrimaryKeyIndex
}) {
static readonly decode = S.decodeEither(this, {
exact: true,
onExcessProperty: 'error'
})
static readonly encode = S.decodeEither(this, {
exact: true,
onExcessProperty: 'error'
})
}
const s = AccountCreate.decode({
name: '1234',
state: 'AAAA',
apiKey: 1234
})
if (E.isLeft(s)) {
const { path } = ParseResult.ArrayFormatter.formatErrorSync(s.left)[0]!
const cause = M.value(path).pipe(
M.when(['name'], () => 'name'),
M.when(['state'], () => 'state'),
M.when(['apiKey'], () => 'apiKey')
)
console.log(`invalid ${cause.value.right}`)
}I’m trying to validate user input, and I’d like to display error messages that correspond to which specific input field is invalid. But I feel like my current implementation might not be the right approach. Do you have any good suggestions?
