question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

findFirstOrThrow / findUniqueOrThrow errors are not reported via `error` event

See original GitHub issue

Bug description

When findFirstOrThrow or findUniqueOrThrow can’t find a model instance, an error is thrown. This error is not currently catchable as it doesn’t trigger a Prisma error event, nor is it thrown by next inside of middlewares.

This is the issue which was described by @bbenezech in this comment and confirmed to be a bug by @janpio .

For us the immediate effect is that the error is not logged by our custom logger, which results in 5 or 6 error lines in Datadog (triggering error alerting).

How to reproduce

  1. Setup a prisma.$on("error", ...) event hook
  2. Setup a prisma.$use(...) middleware
  3. Use the Prisma client to make a findFirstOrThrow query that is guaranteed to fail
  4. The error is thrown and logged directly in console without going through the error event hook, or being thrown inside the middleware

Expected behavior

I would expect one of those two behaviours (or both) :

  • The error event hook is called
  • The error is thrown by next in the middleware so i can catch it and treat it accordingly

Prisma information

This happens for all models but should be reproducible with this minimal schema :

datasource db {
  provider = "postgresql"
  url      = env("DB_URL")
}

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["interactiveTransactions", "orderByNulls"]
}

model User {
  id                 Int                       @id @default(autoincrement())
  email              String                    @unique
}

Client queries :

  const prisma = new PrismaClient({
    datasources: {
      db: {
        url: config.database.url,
      },
    },
    log: [
      { level: "query", emit: "event" },
      { level: "info", emit: "event" },
      { level: "warn", emit: "event" },
      { level: "error", emit: "event" },
    ],
  });


  prisma.$on("info", (event) => {
    log.info(`[prisma] ${event.message}`, {
      target: event.target,
    });
  });

  prisma.$on("warn", (event) => {
    log.warn(`[prisma] ${event.message}`, {
      target: event.target,
    });
  });

  prisma.$on("error", (event) => {
    // This code does not appear to be called when throwing
    log.error(`[prisma] ${event.message}`, {
      target: event.target,
    });
  });

  prisma.$use(async (params, next) => {
    console.log(1, params);
    // here, `params.action` is marked as `findUnique` so we can't determine that an `...OrThrow` variant has been used
    const res = await next(params);
    console.log(2, res);
    // here, `res` is `null`. This line is displayed in console before the error message
    return res;
  });

  // There is no user with ID 0 in db
  const test = await prisma.user.findUniqueOrThrow({ where: { id: 0 } });

  console.log(3, test);

☝️ The above code returns the following in console :

1 {
  args: { where: { id: 0 } },
  dataPath: [],
  runInTransaction: false,
  action: 'findUnique',
  model: 'User'
}
2 null
NotFoundError: No User found

Environment & setup

The code runs on this Docker image : node:16-alpine

  • OS: Alpine Linux
  • Database: PostgreSQL
  • Node.js version: 16.17.0

Prisma Version

prisma                  : 4.2.0
@prisma/client          : 4.2.0
Current platform        : linux-musl
Query Engine (Node-API) : libquery-engine 2920a97877e12e055c1333079b8d19cee7f33826 (at node_modules/@prisma/engines/libquery_engine-linux-musl.so.node)
Migration Engine        : migration-engine-cli 2920a97877e12e055c1333079b8d19cee7f33826 (at node_modules/@prisma/engines/migration-engine-linux-musl)
Introspection Engine    : introspection-core 2920a97877e12e055c1333079b8d19cee7f33826 (at node_modules/@prisma/engines/introspection-engine-linux-musl)
Format Binary           : prisma-fmt 2920a97877e12e055c1333079b8d19cee7f33826 (at node_modules/@prisma/engines/prisma-fmt-linux-musl)
Default Engines Hash    : 2920a97877e12e055c1333079b8d19cee7f33826
Studio                  : 0.469.0
Preview Features        : interactiveTransactions, orderByNulls

Issue Analytics

  • State:closed
  • Created a year ago
  • Reactions:2
  • Comments:6 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
miguelffcommented, Nov 30, 2022

@SpecialAro no need to report anymore. Your report was also captured by https://github.com/prisma/prisma/issues/16549. A fix is on the way. https://github.com/prisma/prisma-engines/pull/3458

1reaction
miguelffcommented, Nov 30, 2022

Hello @SpecialAro!

Though, this approach is undesirable because I’m not using a prisma functionality that is quite useful.

In this case you are not only checking the existence of a jwtSecret, for which you might use the findXOrThrow method, but also checking that in case it exists, its jwtSecret property has a not null value.

For that, I think the appropriate API is the one you suggest, to use findUnique and check manually. It’s more compact, and easier to understand code in my opinion.

Having said that, the error logged in the console informs about a field not present in the model, which should be a bug. Would you mind filing a new bug report, please? and include information for reproduction, including a schema file, so we can help you better?

Thank you.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Prisma Client API (Reference)
From v4.0.0, use the queries findUniqueOrThrow or findFirstOrThrow . ... an error if the record is not found, then consider using findUniqueOrThrow instead....
Read more >
Invalid prisma.project.findUniqueOrThrow() invocation - Stack ...
Calling findUniqueOrThrow is returning the error mentioned in the title. const getProjectOverview = async (req: Request, res: Response) ...
Read more >
Prisma 4.7.0 Release - GitClear
fix(client): remove retries for all errors except network connection/socket ... findUniqueOrThrow errors are not reported via error event ...
Read more >
Prisma 4.0 Released: The Next Gen ORM - Morioh
New Prisma Client APIs: findUniqueOrThrow and findFirstOrThrow ... If a number does not fit, Prisma will throw a P2023 error:
Read more >
@prisma/engines: Versions | Openbase
If you already have a PostgreSQL database using multiple schemas, ... findFirstOrThrow / findUniqueOrThrow errors are not reported via error event ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found