HBForge/Examples
05 · Applications

Validator with structured error responses

Validate request bodies with HBForge's built-in schema builder — Zod-like fluent API, zero dependencies. Failures return a structured error array.

forge/serverNodeBunDenoCF Workers
Code
validator-error-handling.js
const { WebApp, ObjectSchema, StringSchema, NumberSchema } =
  require(class="tk-str">'@hyperbridge/forge/server');

const app = new WebApp();

const User = new ObjectSchema({
  name: new StringSchema().min(1).max(100),
  age:  new NumberSchema().min(0).max(150),
  email: new StringSchema().email(),
});

app.post(class="tk-str">'/users', async (c) => {
  const r = User.validate(await c.req.json());
  if (!r.valid) {
    return c.json({
      error: class="tk-str">'validation_failed',
      issues: r.errors,
    }, 400);
  }
  return c.json({ ok: true, user: r.value }, 201);
});

app.onError((err, c) => c.json({
  error: class="tk-str">'internal_error',
  message: err.message,
}, 500));

app.listen(3000);
How it works

ObjectSchema.validate(data) returns { valid, value, errors }. The error shape matches Zod's safeParse output for easy migration.

Chain methods (.min() · .max() · .email() · .regex() · .optional() · .default()) compose without operator overloading or runtime type tricks.

app.onError() catches anything thrown deeper in the chain — keep handlers small, let the error sink to one place.

Try it
Quickstart
curl -X POST http://localhost:3000/users -d '{"name":"","age":-1}' -H content-type:application/json
Related modules