prisma: `JSON.stringify` loses much of error object information vs using `console.log` on it

Bug description

We have a production service that uses prisma & catches an error thrown from prisma that looks like this:

{
  clientVersion: "3.4.1"
}

How to reproduce

This is the query that triggers the error to be thrown:

try{
const startDate = new Date(Date.now() - 24 * 60 * 60 * 1000);
const limit = 100;

const query = Prisma.sql`
  select url, count(*) as count
  from (
    select distinct "Status"."userIdStr", "Status".url
    from "Status"
    where "Status"."createdAt" > (to_timestamp(${startDate.getTime()} / 1000.0))
        and "Status".url is not null
    ) as distinct_user_url_statuses
  group by url
  having distinct_user_url_statuses.count > 1
  order by count desc  
  limit ${limit}
`;
const data = await prisma.$queryRaw<{ url: string; count: number }[]>(query);
} catch (error){
  // log error
}

Expected behavior

an error to be thrown with a message & code that can help me debug what’s going on

Prisma information

prisma & client 3.4.1

prisma.schema:

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

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

generator client {
  provider = "prisma-client-js"
}

model User {
  idStr String @id 
  name String?
  statuses Status[]
  follows Follow[] @relation("Follower")
  followers Follow[] @relation("Followee")
}

model Follow {
  id Int @id @default(autoincrement())
  userIdStr String
  user User @relation("Follower", fields: [userIdStr], references: [idStr])
  followeeIdStr String
  followee User @relation("Followee", fields: [followeeIdStr], references: [idStr])
  @@unique([userIdStr, followeeIdStr])
}

model Status {
  idStr String @id
  createdAt DateTime
  userIdStr String
  retweetCount Int @default(0)
  favoriteCount Int @default(0)
  user User? @relation(fields: [userIdStr], references: [idStr])
  url String?
  rawJson Json?
}

Environment & setup

  • GCP Cloud Function
  • Database: PostgreSQL 13
  • Node.js version: node v14

Prisma Version

from my local dev environment which is not what’s running in the cloud/prod:

Environment variables loaded from .env
prisma                  : 3.4.1
@prisma/client          : 3.4.1
Current platform        : windows
Query Engine (Node-API) : libquery-engine 57771c0558568c7d08bd34c7248af5244ae16bd9 (at node_modules\@prisma\engines\query_engine-windows.dll.node)
Migration Engine        : migration-engine-cli 57771c0558568c7d08bd34c7248af5244ae16bd9 (at node_modules\@prisma\engines\migration-engine-windows.exe)
Introspection Engine    : introspection-core 57771c0558568c7d08bd34c7248af5244ae16bd9 (at node_modules\@prisma\engines\introspection-engine-windows.exe)
Format Binary           : prisma-fmt 57771c0558568c7d08bd34c7248af5244ae16bd9 (at node_modules\@prisma\engines\prisma-fmt-windows.exe)
Default Engines Hash    : 57771c0558568c7d08bd34c7248af5244ae16bd9
Studio                  : 0.438.0

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 7
  • Comments: 40 (14 by maintainers)

Most upvoted comments

I get same error here, i try to use simple findUniqueOrThrow function like this

try{
        const user = await prisma.user.findUniqueOrThrow({
            where: {
                id: req.params.id
            }
        })
        res.status(200).json({
            data: user
        })
    }catch(error){
        res.status(400).json({
            data: error
        })
    }

i get res like this

   {
  "data": {
    "clientVersion": "4.5.0"
  }
}

but when i throw(error) or console.log(error), i got like this

Invalid `prisma.user.findUniqueOrThrow()` invocation:

{
  where: {
    id: '5'
        ~~~
  }
}

Argument id: Got invalid value '5' on prisma.findUniqueUser. Provided String, expected Int.

I know that error happend because parameter is not Integer, but its helpfull when its return to client maybe like this, error: Got invalid value '5' on prisma.findUniqueUser. Provided String, expected Int.

When this would be fixed? I’m also getting the same thing instead of the proper error message. I’m using "@prisma/client": "^4.2.0"

Hey @janpio

using an invalid DATABASE_URL I continue getting the error when running this script

index.js

const { PrismaClient, Prisma } = require("@prisma/client");

const prisma = new PrismaClient();

async function main() {
  try {
    // the query itself and the schema are irrelevant
    const startDate = new Date(Date.now() - 24 * 60 * 60 * 1000);
    const limit = 100;

    const query = Prisma.sql`
      select url, count(*) as count
      from (
        select distinct "Status"."userIdStr", "Status".url
        from "Status"
        where "Status"."createdAt" > (to_timestamp(${startDate.getTime()} / 1000.0))
            and "Status".url is not null
        ) as distinct_user_url_statuses
      group by url
      having distinct_user_url_statuses.count > 1
      order by count desc  
      limit ${limit}
    `;
    const data = await prisma.$queryRaw(query);
  } catch (error) {
    console.log("keys: ", Object.keys(error));
    console.log("error.errorCode: ", error.errorCode);
    console.error(JSON.stringify(error, null, 2));

    console.log("------------------");
    console.log(error);
  }
}

here is the output:

keys:  [ 'clientVersion', 'errorCode' ]
error.errorCode:  undefined
{
  "clientVersion": "4.5.0"
}
------------------
PrismaClientInitializationError:
Invalid `prisma.$queryRaw()` invocation:


Can't reach database server at `localhost`:`5432`

Please make sure your database server is running at `localhost`:`5432`.
    at RequestHandler.handleRequestError (C:\Users\olear\github\prisma-repro\node_modules\@prisma\client
\runtime\index.js:30879:13)
    at RequestHandler.request (C:\Users\olear\github\prisma-repro\node_modules\@prisma\client\runtime\in
dex.js:30856:12)
    at async Proxy._request (C:\Users\olear\github\prisma-repro\node_modules\@prisma\client\runtime\inde
x.js:31836:16)
    at async main (C:\Users\olear\github\prisma-repro\index.js:23:18) {
  clientVersion: '4.5.0',
  errorCode: undefined
}

If the user is able to inspect the console they can see an intelligent error message (below the separator), but if instead the error is being sent to a client (as in @whytrno’s example) or relayed using some other method (like the GCP logger) this message is lost as the caught error object does not contain this information. The error object contains only: {"clientVersion": "4.5.0"} in the example above which is not particularly useful while debugging.

If you run the same script on your computer does logging out the stringified error object product a different result?

Env info: node v16.15.0 “prisma”: “^4.5.0”, window 11 git bash

also @rj-xy apologies, I missed your question. No I am not using any transpile step in the above script.

No, an update would manifest itself in a message in this comment thread. We are aware of the problem, and will try to reproduce and then potentially fix when we are done with other, higher priority work.

Yes, that would be neat 👍

Yup, when I first created this issue I didn’t realize that was what was happening, but the issue can be boiled down to:

using JSON.stringigy on the error object loses a lot of information vs. just using console.log on it.

Let me know if you’d like me to update the title of the issue to make it more representative.

Hi @SevInf SevInf my issue no longer exists. Thanks

@janpio on my end, the problem was not exactly coming necessarily from raw queries, I made the issue #11385 specifying my problem. I found a way around it and documented on the issue.

@bablukpik we would really love if we could fix it, but unfortunately, information posted in this ticket is not enough to pinpoint it. Are you using babel? If yes, could you share you config, babel & its plugins version? If not, could you provide a small repo where we could see the bug happening?

@koprivajakub Can you please open a new issue about this? Seems unrelated to me but we definitely want to debug and understand this. Thanks!

I was trying to simulate it on a simple debuggable repository. It actually works there correctly, which made me think. I cleaned the yarn cache, deleted node_modules, reinstalled dependencies and now it seems to work without a single change in the code. Not sure what was causing this. I consider this to be resolved for now 🤷‍♂️ BTW: I am using yarn 3.1.0 with nodeLinker: node-modules If I will encounter it again I will open another issue. Thanks for the answer anyway.

@janpio Thanks for putting together that script.

When I run the same locally I see that error in the console, but because this is running on GCP cloud functions, it’s the error object that we log and can actually see.

When I modify your script slightly (the catch block) to add this:

catch (error) {
  console.log('keys: ', Object.keys(error));
  console.log('error.errorCode: ', error.errorCode);
  console.error(JSON.stringify(error, null, 2));
}

I get this output:

keys:  [ 'clientVersion', 'errorCode' ]
error.errorCode:  undefined
{
  "clientVersion": "3.4.1"
}

I would expect this error object to contain information that is useful to me while attempting to debug the error.

@janpio thank you for looking into this. I’ve created the new issue with requested infos => https://github.com/prisma/prisma/issues/10221

I emailed you @janpio

@koprivajakub Can you please open a new issue about this? Seems unrelated to me but we definitely want to debug and understand this. Thanks!

@gheorghemolnar That also sounds unrelated to me, and needs its own issue. Please make sure to fill the issue template so we have all the information to reproduce. Thanks!

@samparmenter @jsw Exit on startup with no error message or hanging also seem unrelated to me - please open a new issue and fill all the information. 3.4.0 to 3.4.1 should definitely not cause any of this as almost nothing changed, so we definitely want to look into this as soon as possible. Thanks!