Nuxt:如何自定义 prisma 错误并将此自定义与 useFetch 一起使用?

问题描述 投票:0回答:1

我的目的是在后端使用 prisma 并在前端使用 nuxt useFetch 在 mysql 数据库中创建一个人。

目前前端如下

type Schema = z.output<typeof schema>;
type person = {
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  memberSince: string;
  memberLastYear: string;
};
const state: person = reactive({
  firstName: "",
  lastName: "",
  email: "",
  phone: "",
  memberSince: "",
  memberLastYear: "",
});

async function onSubmit(event: FormSubmitEvent<any>) {
  console.log("submit");

  const { data, pending, error } = await useFetch("api/person", {
    method: "POST",
    body: event.data,
  });

  if (data) {
    console.log("logging data");
    console.log(toRaw(data.value));
    personsStore.addPerson(toRaw(data.value));
  }
  if (error) {
    console.log("logging error");
    console.log(error.value);
  }

  emit("close");
}

代码位于前端模态中,其中包含表单,因此带有最终的emit('close')语句的onSubmit函数。

在 prima 模式中,有一个唯一的约束来防止用户创建 2 个具有相同名字和姓氏的人。

model Person {

  id      Int      @id @default(autoincrement())
  firstName String @db.VarChar(70)
  lastName String @db.VarChar(70)
  email   String   @db.VarChar(255)
  phone String @db.VarChar (20)
  memberSince DateTime  @db.Date
  memberLastYear String @db.VarChar(10)

  @@unique([firstName,lastName], name:"fullName")

}

目前我终点的代码是这样的

import { PrismaClient, Prisma } from "@prisma/client";
const prisma = new PrismaClient();
export default defineEventHandler(async (event) => {
  const body = await readBody(event);

  console.log("in backend create person");
 
  let memberSince = new Date(body.memberSince);
 try{
      const person = await prisma.person.create({
      data: {
        firstName: body.firstName,
        lastName: body.lastName,
        email: body.email,
        phone: body.phone,
        memberSince: memberSince,
        memberLastYear: body.memberLastYear,
      },
    });
     return person
 } catch(e){
   throw new Error('something went wrong when creating the person in the database')
 }
});

我打算研究 catch 部分,以便在用户尝试创建重复对(名字姓氏)时抛出自定义消息 我尝试了很多事情但从未成功。我需要一些帮助来在这里编写 catch 子句,还需要一些帮助来了解如何在前端检索此消息。

目前我什至无法收到自定义消息,即“在数据库中创建人员时出现问题”,但只能收到原始错误消息“错误:[POST]“api/person”:500内部服务器错误”

提前致谢。

nuxt.js prisma
1个回答
0
投票

经过一段时间的斗争,我找到了这个解决方案(可能不是最好的或最正统的,但它有效)

import { PrismaClient, Prisma } from "@prisma/client";
const prisma = new PrismaClient();
export default defineEventHandler(async (event) => {
  const body = await readBody(event);

  console.log("in backend create person");

  let memberSince = new Date(body.memberSince);
  let person = null;
 
  await prisma.person
    .create({
      data: {
        firstName: body.firstName,
        lastName: body.lastName,
        email: body.email,
        phone: body.phone,
        memberSince: memberSince,
        memberLastYear: body.memberLastYear,
      },
    })
    .then((response) => {
      person = response;
    })
    .catch((error) => {
      if (error instanceof Prisma.PrismaClientKnownRequestError) {
        // The .code property can be accessed in a type-safe manner
        if (error.code === "P2002") {
          error = createError({
            statusCode: 500,
            statusMessage: "Duplicate fullName not accepted",
          }); 
        }
      }
      throw error;
    });
  return person;
});
© www.soinside.com 2019 - 2024. All rights reserved.