Skip to content

RejectPerModel always returns instance of Error #13497

Open

Description

@zomars

Bug description

Having a global rejectOnNotFound doesn't respect the type of error returned. Instead it always returns a generic Error

He have a custom error where we can attach more info:

export class HttpError<TCode extends number = number> extends Error {
  public readonly cause?: Error;
  public readonly statusCode: TCode;
  public readonly message: string;
  public readonly url: string | undefined;
  public readonly method: string | undefined;

  constructor(opts: { url?: string; method?: string; message?: string; statusCode: TCode; cause?: Error }) {
    super(opts.message ?? `HTTP Error ${opts.statusCode} `);

    Object.setPrototypeOf(this, HttpError.prototype);
    this.name = HttpError.prototype.constructor.name;

    this.cause = opts.cause;
    this.statusCode = opts.statusCode;
    this.url = opts.url;
    this.method = opts.method;
    this.message = opts.message ?? `HTTP Error ${opts.statusCode}`;

    if (opts.cause instanceof Error && opts.cause.stack) {
      this.stack = opts.cause.stack;
    }
  }

}

And we use it consistently like this:

export const prisma = new PrismaClient({
  rejectOnNotFound: {
    findUnique: {
      User: () => new HttpError({ statusCode: 404, message: "User not found" }),
    },
  },
});
try {
    await prisma.user.findUnique({ where: { id: 1 } });
  } catch (err) {
    if (err instanceof HttpError) {
      console.log("This won't log, but it should!");
    } else if (err instanceof Prisma.PrismaClientKnownRequestError) {
      console.log("This won't log");
    } else if (err instanceof Error) {
      console.log("This WILL log but we don't have the HttpError data");
    } else {
      console.log("This won't log");
    }
  }
};

How to reproduce

Use the code mentioned in the description

Expected behavior

We expect to return the actual HttpError instead on the generic Error class.

This is what logging the err object shows:

Error HttpError: User not found
    at User (webpack-internal:///(api)/./modules/common/utils/prisma.ts:20:23)
    at throwIfNotFound (/Users/user/dev/project/node_modules/@prisma/client/runtime/index.js:45292:13)
    at Object.request (/Users/user/dev/project/node_modules/@prisma/client/runtime/index.js:45385:7)
    at async PrismaClient._request (/Users/user/dev/project/node_modules/@prisma/client/runtime/index.js:46301:18)
    at async getHandler (webpack-internal:///(api)/./modules/dashboard/api/usage/_get.ts:30:18)
    at async eval (webpack-internal:///(api)/./modules/common/api/defaultResponder.ts:21:28)
    at async eval (webpack-internal:///(api)/./modules/common/api/defaultHandler.ts:13:13)
    at async Object.apiResolver (/Users/user/dev/project/node_modules/next/dist/server/api-utils/node.js:185:9)
    at async DevServer.runApi (/Users/user/dev/project/node_modules/next/dist/server/next-server.js:395:9)
    at async Object.fn (/Users/user/dev/project/node_modules/next/dist/server/base-server.js:496:37) {
  cause: undefined,
  statusCode: 404,
  url: undefined,
  method: undefined,
  clientVersion: '3.14.0'
}

Prisma information

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["filterJson"]
}

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

model User {
  id            Int       @id @unique
  name          String?
  metadata      Json?
  createdAt     DateTime  @default(now())
  updatedAt     DateTime  @default(now()) @updatedAt
}

Environment & setup

  • OS: Mac OS
  • Database: PostgreSQL
  • Node.js version: v14.17.6

Prisma Version

prisma                  : 3.14.0
@prisma/client          : 3.14.0
Current platform        : darwin
Query Engine (Node-API) : libquery-engine 2b0c12756921c891fec4f68d9444e18c7d5d4a6a (at node_modules/@prisma/engines/libquery_engine-darwin.dylib.node)
Migration Engine        : migration-engine-cli 2b0c12756921c891fec4f68d9444e18c7d5d4a6a (at node_modules/@prisma/engines/migration-engine-darwin)
Introspection Engine    : introspection-core 2b0c12756921c891fec4f68d9444e18c7d5d4a6a (at node_modules/@prisma/engines/introspection-engine-darwin)
Format Binary           : prisma-fmt 2b0c12756921c891fec4f68d9444e18c7d5d4a6a (at node_modules/@prisma/engines/prisma-fmt-darwin)
Default Engines Hash    : 2b0c12756921c891fec4f68d9444e18c7d5d4a6a
Studio                  : 0.460.0

Activity

  1. added
    kind/bug
    on May 25, 2022
  2. added
    bug/1-unconfirmed
    on May 26, 2022
  3. added
    bug/2-confirmed
    and removed
    bug/1-unconfirmed
    on May 27, 2022
  4. pantharshit00 commented on May 27, 2022

    @pantharshit00
    Contributor

    I can confirm the but we are actually planning to rework rejectOnNotFound so maybe leave a comment here: #12159

  5. garrensmith commented on Jul 1, 2022

    @garrensmith
    Contributor

    Since we've deprecated this API, we're not planning on supporting this API much longer. Could you try the findUniqueOrThrow replacement and let us know how that goes?

  6. self-assigned this
    on Oct 21, 2022
  7. SevInf commented on Oct 21, 2022

    @SevInf
    Contributor

    Can not reproduce it, neither on current dev, nor on reported 3.14 version. Here is the code I am tryng:

    import { PrismaClient } from '.prisma/client'
    
    class HttpError extends Error {
      constructor() {
        super('Http error!')
        Object.setPrototypeOf(this, HttpError.prototype)
    
        Error.captureStackTrace(this, HttpError)
      }
    }
    
    async function main() {
      const prisma = new PrismaClient({
        rejectOnNotFound: {
          findUnique: {
            User: () => new HttpError(),
          },
        },
      })
    
      try {
        await prisma.user.findUnique({ where: { id: 'not-here' } })
      } catch (e) {
        console.log(e instanceof HttpError)
      }
    }
    
    void main().catch((e) => {
      console.log(e.message)
      process.exit(1)
    })

    This always logs true for me. @zomars could you share a repo where it reliably reproduces?

  8. removed their assignment
    on Nov 10, 2022
  9. janpio commented on Jul 4, 2023

    @janpio
    Contributor

    Ping @zomars.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug/2-confirmedkind/bugtopic: errortopic: rejectOnNotFound / *OrThrow

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions