Simon
Simon
TtRPC
Created by Simon on 5/9/2025 in #❓-help
Throw Validation error inside the procedure?
Yeah that's what I'm doing currently. Wraping into a TRPCError + errorFormatter that is already used for the input validation. Thought there would be an easier solution, but that's still fine enough:
export async function validate(
path: string,
condition: boolean | (() => Promise<boolean>),
message: string = "",
) {
try {
type({
[path]: type("true").configure({
message: message ?? "Invalid value.",
}),
}).assert({
[path]: typeof condition === "function" ? await condition() : condition,
});
} catch (e) {
throw new TRPCError({
code: "BAD_REQUEST",
cause: e,
});
}
}
export async function validate(
path: string,
condition: boolean | (() => Promise<boolean>),
message: string = "",
) {
try {
type({
[path]: type("true").configure({
message: message ?? "Invalid value.",
}),
}).assert({
[path]: typeof condition === "function" ? await condition() : condition,
});
} catch (e) {
throw new TRPCError({
code: "BAD_REQUEST",
cause: e,
});
}
}
3 replies