npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

koa-zod-errorhandler

v1.0.0

Published

A simple koa middleware for handling zod errors

Downloads

5

Readme

koa-zod-errorhandler

A simple koa middleware that handles zod parse errors.

📕 TL;DR:

  • automatically catches ZodErrors, so you don't need to
  • returns a 400 Bad Request with a default response
  • allows you to customize the error and logging behaviour

💡 About

This Koa middleware allows you validate input using zods parse() function without the need to try/catch. It detects ZodErrors and by default returns a 400 Bad Request with a payload containing the fields that caused validation errors:

{
  "error": "Bad Request",
  "detail": {
    "name": "Invalid input"
  }
}

Using this middleware can make your code more concise and easier to read, as you don't need to add try/catch blocks for ZodErrors. It can also help you standardize the error handling in your Koa application.

Installation

Add the middleware to your dependencies (make sure you have zod in your dependencies):

# Yarn
yarn add koa-zod-errorhandler

# npm
npm install koa-zod-errorhandler

Add the middleware to your koa instance:

const app = new Koa();

/// ... etc ...

app.use(zodErrorHandler());

// or provide extra options
app.use(
  zodErrorHandler({
    log: myLogFn,
    transformResponse: myResponseTransformer,
  })
);

Validate using zod (no special code needed for the middleware):

router.post('/', bodyParser(), (ctx) => {
  const bodyPayload = z
    .object({
      name: z.string(),
    })
    .parse(ctx.request.body);

  // do something
  ctx.response.status = 200;
});

🛠️ Options

The middleware takes an optional object with the following options:

  • log: (boolean or logger function, default: false):
    Modify the way zod errors are logged.
    This can be either a function that handles logging in a custom way or a boolean that indicates whether logging (using console.log) should be activated or not. Logging is disabled by default.

    Log functions get the ZodError as the first argument and the Koa.Context as the second, allowing you to log additional information about a request.

    export type Logger = (error: ZodError, ctx: Koa.Context) => void;

    Example: Using your own logger

    app.use(
      zodErrorHandler({
        log: (error: ZodError) => {
          myLogger.debug({ traceId: myTraceId, error }, 'A user provided an invalid payload');
        },
      })
    );
  • transformResponse: (transform function, default: undefined)
    Transform the ZodError for the response and set additional values like headers in the Koa context if you need to.

    Transformer functions get the ZodError as the first argument and the Koa.Context as the second, allowing you to modify the response further. They expect you to return an object or an string.

    export type ResponseTransformer = (error: ZodError, ctx: Koa.Context) => object | string;

    Example: Return a response without any information to the user

    app.use(
      zodErrorHandler({
        transformResponse: (_error: ZodError, ctx: Koa.Context) => {
          // act like the ressource does not exist
          ctx.status = 404;
          return { error: 'Resource not found' };
        },
      })
    );

Maintainers

@mojadev

Contributing

Feel free to dive in! Open an issue or submit PRs.

License

MIT © Jannis Gansen