Похожие чаты

Initially I did this so the errors don't leak to

the client (in case they contain sensitive data), but something in my guts is telling me this is stupid to catch the error and throw it again (although I've seen a similar pattern somewhere else)

Any recommendations?

export async function fetchFilteredPacks(query: string, currentPage: number) {
  try {
    const authResult = await auth();

    if (!authResult?.user) throw new AuthError();

    const skip = (currentPage - 1) * TAKE;

    const data = await db.pack.findMany({
      orderBy: { updatedAt: "desc" },
      where: {
        OR: [
          { description: { contains: query } },
          { name: { contains: query } },
          { url: { contains: query } },
        ],
      },
      take: TAKE,
      skip: skip,
    });

    return data;
  } catch (error) {
    console.error(error);

    if (error instanceof AuthError) throw new Error("Unauthorized");

    throw new Error("Failed to fetch packs");
  }
}

7 ответов

12 просмотров

You can just isolate the auth part, otherwise it's fine

I might move the try catch outside this function

Senator- Автор вопроса
Thomas
You can just isolate the auth part, otherwise it's...

Do you mean that I should put it in its own try-catch and rethrow or return if the user isn't signed in?

Senator
Do you mean that I should put it in its own try-ca...

Like move the auth call and check to before the try catch

Senator- Автор вопроса
Thomas
I might move the try catch outside this function

I'm using Next.js, and currently this function is used in my /packs route that is already checking for the auth state and also handles the errors, but I wanted to future proof it just in case I use it in another place and I want it to throw but not leak sensitive data

Keep fetchFilteredPacks as it was, make a new one like: authAndFetchFilteredPacksHideErrors

Похожие вопросы

Обсуждают сегодня

Какой-то там пердун в 90-х решил, что есть какая-то разная типизация. Кого вообще это волнует?
КТ315
49
Hi. Do we have a raid bot? Why nobody doing raids on X? Even RH mentioned this and nobody paying attention...whats the channel for hex memes? If mods cant run raids just insta...
H
31
Подскажите, а есть vault lite или ченить такое?) А то нужен вольт для похода в вольт, но весит он ~500 мб) как-то многовато для парочки запросов ))
Alexandr Orloff
17
блеать, почему так?? где в роутере это исправляется?
Арсен Маньяков 🇦🇲
16
void terminal_scroll() { memmove(terminal_buffer, terminal_buffer + VGA_WIDTH, buffer_size - VGA_WIDTH); memset(terminal_buffer + buffer_size - VGA_WIDTH, 0, VGA_WIDTH); ...
Егор
47
🌊 Ocean Nodes Dashboard Update 🚀 Hey, Oceaners! First off, a massive round of applause 👏to all of you for the amazing engagement since we launched Ocean Nodes. In just a few ...
KreigDK | Never DM first🌊
3
Всем привет! Подскажите, пожалуйста, в чем ошибка? Настраиваю подключение к MySQL. Либы лежат рядом с exe. Все как по "учебнику"
Евгений
16
А можете как-то проверить меня по знаниям по ассемблеру?
A A
132
Здравствуйте! У меня появилась возможность купить книгу "Изучай Haskell во имя добра!". Но я где-то слышал, что эта книга устарела. Насколько это правда??
E
22
люди, которые используют flameshot, к вам вопрос. Можно-ли поставить хоткей на создание скриншота? В программе есть отдел "горячие клавиши", но там все для редактирования, скр...
ThunDer104
11
Карта сайта