refactor: better observability in api routes (#18810)

Co-authored-by: Keith Williams <[email protected]>
This commit is contained in:
Omar LópezandKeith Williams authored and GitHub committed 2025-01-22 20:52:09 +00:00
1 parent 35565c8f7e
commit 1af3caa8cc
3 files changed
+17 -4

No files matched your search

+1 -2
View File
@@ -1,4 +1,3 @@
import { wrapApiHandlerWithSentry } from "@sentry/nextjs";
import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
@@ -30,4 +29,4 @@ async function handler(req: NextApiRequest & { userId?: number }, res: NextApiRe
return booking;
}
export default defaultResponder(wrapApiHandlerWithSentry(handler, "/api/book/event"));
export default defaultResponder(handler, "/api/book/event");
+9 -2
View File
@@ -1,3 +1,4 @@
import { wrapApiHandlerWithSentry } from "@sentry/nextjs";
import type { NextApiRequest, NextApiResponse } from "next";
import { getServerErrorFromUnknown } from "./getServerErrorFromUnknown";
@@ -6,12 +7,18 @@ import { performance } from "./perfObserver";
type Handle<T> = (req: NextApiRequest, res: NextApiResponse) => Promise<T>;
/** Allows us to get type inference from API handler responses */
export function defaultResponder<T>(f: Handle<T>) {
export function defaultResponder<T>(
f: Handle<T>,
/** If set we will wrap the handle with sentry tracing */
endpointRoute?: string
) {
return async (req: NextApiRequest, res: NextApiResponse) => {
let ok = false;
try {
performance.mark("Start");
const result = await f(req, res);
const result = endpointRoute
? await wrapApiHandlerWithSentry(f, endpointRoute)(req, res)
: await f(req, res);
ok = true;
if (result && !res.writableEnded) {
return res.json(result);
@@ -3,6 +3,9 @@ import Stripe from "stripe";
import type { ZodIssue } from "zod";
import { ZodError } from "zod";
import { TRPCError } from "@trpc/server";
import { getHTTPStatusCodeFromError } from "@trpc/server/http";
import { HttpError } from "../http-error";
import { redactError } from "../redactError";
@@ -31,6 +34,10 @@ function parseZodErrorIssues(issues: ZodIssue[]): string {
}
export function getServerErrorFromUnknown(cause: unknown): HttpError {
if (cause instanceof TRPCError) {
const statusCode = getHTTPStatusCodeFromError(cause);
return new HttpError({ statusCode, message: cause.message });
}
if (isZodError(cause)) {
return new HttpError({
statusCode: 400,