Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

chore(trpc): remove redundant try catch blocks (#10061)

marliessophieaed4f2a5e50c
diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.ts
index 706a839853..2004a8d373 100644
--- a/web/src/features/dashboard/server/dashboard-router.ts
+++ b/web/src/features/dashboard/server/dashboard-router.ts
@@ -167,27 +167,18 @@ export const dashboardRouter = createTRPCRouter({
try {
return executeQuery(input.projectId, input.query as QueryType);
} catch (error) {
- // If the error is a known invalid request, return a 400 error
if (error instanceof InvalidRequestError) {
logger.warn("Bad request in query execution", error, {
projectId: input.projectId,
query: input.query,
});
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: error.message || "Invalid request",
- cause: error,
- });
+ throw error;
}
logger.error("Error executing query", error, {
projectId: input.projectId,
query: input.query,
});
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Failed to execute query",
- cause: error,
- });
+ throw error;
}
}),
diff --git a/web/src/features/evals/server/defaultEvalModelRouter.ts b/web/src/features/evals/server/defaultEvalModelRouter.ts
index 98a1e87f5d..71da04638f 100644
--- a/web/src/features/evals/server/defaultEvalModelRouter.ts
+++ b/web/src/features/evals/server/defaultEvalModelRouter.ts
@@ -4,14 +4,8 @@ import {
protectedProjectProcedure,
} from "@/src/server/api/trpc";
import { z } from "zod/v4";
-import {
- ForbiddenError,
- InvalidRequestError,
- LangfuseNotFoundError,
- ZodModelConfig,
-} from "@langfuse/shared";
+import { ZodModelConfig } from "@langfuse/shared";
import { DefaultEvalModelService } from "@langfuse/shared/src/server";
-import { TRPCError } from "@trpc/server";
export const defaultEvalModelRouter = createTRPCRouter({
fetchDefaultModel: protectedProjectProcedure
@@ -42,18 +36,7 @@ export const defaultEvalModelRouter = createTRPCRouter({
scope: "evalDefaultModel:CUD",
});
- try {
- return await DefaultEvalModelService.upsertDefaultModel(input);
- } catch (error) {
- if (error instanceof InvalidRequestError) {
- throw new TRPCError({ code: "BAD_REQUEST", message: error.message });
- } else if (error instanceof LangfuseNotFoundError) {
- throw new TRPCError({ code: "NOT_FOUND", message: error.message });
- } else if (error instanceof ForbiddenError) {
- throw new TRPCError({ code: "FORBIDDEN", message: error.message });
- }
- throw error;
- }
+ return DefaultEvalModelService.upsertDefaultModel(input);
}),
deleteDefaultModel: protectedProjectProcedure
.input(z.object({ projectId: z.string() }))
diff --git a/web/src/features/evals/server/router.ts b/web/src/features/evals/server/router.ts
index f748afd247..2c012c4c52 100644
--- a/web/src/features/evals/server/router.ts
+++ b/web/src/features/evals/server/router.ts
@@ -598,41 +598,30 @@ export const evalRouter = createTRPCRouter({
evaluatorsByTemplateName: protectedProjectProcedure
.input(z.object({ projectId: z.string(), evalTemplateName: z.string() }))
.query(async ({ input, ctx }) => {
- try {
- throwIfNoProjectAccess({
- session: ctx.session,
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "evalJob:read",
+ });
+
+ const templates = await ctx.prisma.evalTemplate.findMany({
+ where: {
projectId: input.projectId,
- scope: "evalJob:read",
- });
+ name: input.evalTemplateName,
+ },
+ select: {
+ id: true,
+ },
+ });
- const templates = await ctx.prisma.evalTemplate.findMany({
+ return {
+ evaluators: await ctx.prisma.jobConfiguration.findMany({
where: {
projectId: input.projectId,
- name: input.evalTemplateName,
+ evalTemplateId: { in: templates.map((t) => t.id) },
},
- select: {
- id: true,
- },
- });
-
- return {
- evaluators: await ctx.prisma.jobConfiguration.findMany({
- where: {
- projectId: input.projectId,
- evalTemplateId: { in: templates.map((t) => t.id) },
- },
- }),
- };
- } catch (error) {
- logger.error(error);
- if (error instanceof TRPCError) {
- throw error;
- }
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Fetching eval jobs for template failed.",
- });
- }
+ }),
+ };
}),
jobConfigsByTarget: protectedProjectProcedure
@@ -660,130 +649,114 @@ export const evalRouter = createTRPCRouter({
jobConfigsByTemplateName: protectedProjectProcedure
.input(z.object({ projectId: z.string(), evalTemplateName: z.string() }))
.query(async ({ input, ctx }) => {
- try {
- throwIfNoProjectAccess({
- session: ctx.session,
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "evalJob:read",
+ });
+
+ const templates = await ctx.prisma.evalTemplate.findMany({
+ where: {
projectId: input.projectId,
- scope: "evalJob:read",
- });
+ name: input.evalTemplateName,
+ },
+ select: {
+ id: true,
+ },
+ });
- const templates = await ctx.prisma.evalTemplate.findMany({
+ return {
+ evaluators: await ctx.prisma.jobConfiguration.findMany({
where: {
projectId: input.projectId,
- name: input.evalTemplateName,
+ evalTemplateId: { in: templates.map((t) => t.id) },
},
- select: {
- id: true,
- },
- });
-
- return {
- evaluators: await ctx.prisma.jobConfiguration.findMany({
- where: {
- projectId: input.projectId,
- evalTemplateId: { in: templates.map((t) => t.id) },
- },
- }),
- };
- } catch (error) {
- logger.error(error);
- if (error instanceof TRPCError) {
- throw error;
- }
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Fetching eval jobs for template failed.",
- });
- }
+ }),
+ };
}),
createJob: protectedProjectProcedure
.input(CreateEvalJobSchema)
.mutation(async ({ input, ctx }) => {
- try {
- throwIfNoProjectAccess({
- session: ctx.session,
- projectId: input.projectId,
- scope: "evalJob:CUD",
- });
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "evalJob:CUD",
+ });
- const evalTemplate = await ctx.prisma.evalTemplate.findUnique({
- where: {
- id: input.evalTemplateId,
- OR: [{ projectId: input.projectId }, { projectId: null }],
- },
- });
+ const evalTemplate = await ctx.prisma.evalTemplate.findUnique({
+ where: {
+ id: input.evalTemplateId,
+ OR: [{ projectId: input.projectId }, { projectId: null }],
+ },
+ });
- if (!evalTemplate) {
- logger.warn(
- `Template not found for project ${input.projectId} and id ${input.evalTemplateId}`,
- );
- throw new Error("Template not found");
- }
+ if (!evalTemplate) {
+ logger.warn(
+ `Template not found for project ${input.projectId} and id ${input.evalTemplateId}`,
+ );
+ throw new Error("Template not found");
+ }
- const jobId = uuidv4();
- await auditLog({
- session: ctx.session,
- resourceType: "job",
- resourceId: jobId,
- action: "create",
- });
+ const jobId = uuidv4();
+ await auditLog({
+ session: ctx.session,
+ resourceType: "job",
+ resourceId: jobId,
+ action: "create",
+ });
- const job = await ctx.prisma.jobConfiguration.create({
- data: {
- id: jobId,
- projectId: input.projectId,
- jobType: "EVAL",
- evalTemplateId: input.evalTemplateId,
- scoreName: input.scoreName,
- targetObject: input.target,
- filter: input.filter ?? [],
- variableMapping: input.mapping,
- sampling: input.sampling,
- delay: input.delay,
- status: "ACTIVE",
- timeScope: input.timeScope,
- },
- });
+ const job = await ctx.prisma.jobConfiguration.create({
+ data: {
+ id: jobId,
+ projectId: input.projectId,
+ jobType: "EVAL",
+ evalTemplateId: input.evalTemplateId,
+ scoreName: input.scoreName,
+ targetObject: input.target,
+ filter: input.filter ?? [],
+ variableMapping: input.mapping,
+ sampling: input.sampling,
+ delay: input.delay,
+ status: "ACTIVE",
+ timeScope: input.timeScope,
+ },
+ });
- // Clear the "no job configs" cache since we just created a new job configuration
- await clearNoJobConfigsCache(input.projectId);
+ // Clear the "no job configs" cache since we just created a new job configuration
+ await clearNoJobConfigsCache(input.projectId);
- if (input.timeScope.includes("EXISTING")) {
- logger.info(
- `Applying to historical traces for job ${job.id} and project ${input.projectId}`,
- );
- const batchJobQueue = getQueue(QueueName.BatchActionQueue);
- if (!batchJobQueue) {
- throw new Error("Batch job queue not found");
- }
- await batchJobQueue.add(
- QueueJobs.BatchActionProcessingJob,
- {
- name: QueueJobs.BatchActionProcessingJob,
- timestamp: new Date(),
- id: uuidv4(),
- payload: {
- projectId: input.projectId,
- actionId: "eval-create",
- configId: job.id,
- cutoffCreatedAt: new Date(),
- targetObject: input.target,
- query: {
- filter: input.filter ?? [],
- orderBy: {
- column: "timestamp",
- order: "DESC",
- },
+ if (input.timeScope.includes("EXISTING")) {
+ logger.info(
+ `Applying to historical traces for job ${job.id} and project ${input.projectId}`,
+ );
+ const batchJobQueue = getQueue(QueueName.BatchActionQueue);
+ if (!batchJobQueue) {
+ throw new Error("Batch job queue not found");
+ }
+ await batchJobQueue.add(
+ QueueJobs.BatchActionProcessingJob,
+ {
+ name: QueueJobs.BatchActionProcessingJob,
+ timestamp: new Date(),
+ id: uuidv4(),
+ payload: {
+ projectId: input.projectId,
+ actionId: "eval-create",
+ configId: job.id,
+ cutoffCreatedAt: new Date(),
+ targetObject: input.target,
+ query: {
+ filter: input.filter ?? [],
+ orderBy: {
+ column: "timestamp",
+ order: "DESC",
},
},
},
- { delay: input.delay },
- );
- }
- } catch (e) {
- logger.error(e);
- throw e;
+ },
+ { delay: input.delay },
+ );
}
}),
createTemplate: protectedProjectProcedure
diff --git a/web/src/features/prompts/server/routers/promptRouter.ts b/web/src/features/prompts/server/routers/promptRouter.ts
index d2f06bf358..b8873c3520 100644
--- a/web/src/features/prompts/server/routers/promptRouter.ts
+++ b/web/src/features/prompts/server/routers/promptRouter.ts
@@ -12,7 +12,6 @@ import { createPrompt, duplicatePrompt } from "../actions/createPrompt";
import { checkHasProtectedLabels } from "../utils/checkHasProtectedLabels";
import {
CreatePromptTRPCSchema,
- InvalidRequestError,
LATEST_PROMPT_LABEL,
optionalPaginationZod,
paginationZod,
@@ -276,61 +275,50 @@ export const promptRouter = createTRPCRouter({
create: protectedProjectProcedure
.input(CreatePromptTRPCSchema)
.mutation(async ({ input, ctx }) => {
- try {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "prompts:CUD",
+ });
+
+ const { hasProtectedLabels, protectedLabels } =
+ await checkHasProtectedLabels({
+ prisma: ctx.prisma,
+ projectId: input.projectId,
+ labelsToCheck: input.labels,
+ });
+
+ if (hasProtectedLabels) {
throwIfNoProjectAccess({
session: ctx.session,
projectId: input.projectId,
- scope: "prompts:CUD",
+ scope: "promptProtectedLabels:CUD",
+ forbiddenErrorMessage: `You don't have permission to create a prompt with a protected label. Please contact your project admin for assistance.\n\n Protected labels are: ${protectedLabels.join(", ")}`,
});
+ }
- const { hasProtectedLabels, protectedLabels } =
- await checkHasProtectedLabels({
- prisma: ctx.prisma,
- projectId: input.projectId,
- labelsToCheck: input.labels,
- });
-
- if (hasProtectedLabels) {
- throwIfNoProjectAccess({
- session: ctx.session,
- projectId: input.projectId,
- scope: "promptProtectedLabels:CUD",
- forbiddenErrorMessage: `You don't have permission to create a prompt with a protected label. Please contact your project admin for assistance.\n\n Protected labels are: ${protectedLabels.join(", ")}`,
- });
- }
-
- const prompt = await createPrompt({
- ...input,
- prisma: ctx.prisma,
- createdBy: ctx.session.user.id,
- });
+ const prompt = await createPrompt({
+ ...input,
+ prisma: ctx.prisma,
+ createdBy: ctx.session.user.id,
+ });
- if (!prompt) {
- throw new Error("Failed to create prompt");
- }
+ if (!prompt) {
+ throw new Error("Failed to create prompt");
+ }
- await auditLog(
- {
- session: ctx.session,
- resourceType: "prompt",
- resourceId: prompt.id,
- action: "create",
- after: prompt,
- },
- ctx.prisma,
- );
+ await auditLog(
+ {
+ session: ctx.session,
+ resourceType: "prompt",
+ resourceId: prompt.id,
+ action: "create",
+ after: prompt,
+ },
+ ctx.prisma,
+ );
- return prompt;
- } catch (e) {
- logger.error(e);
- if (e instanceof InvalidRequestError) {
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: e.message,
- });
- }
- throw e;
- }
+ return prompt;
}),
duplicatePrompt: protectedProjectProcedure
.input(
diff --git a/web/src/server/api/routers/comments.ts b/web/src/server/api/routers/comments.ts
index 8a11ae6c65..a23c68384d 100644
--- a/web/src/server/api/routers/comments.ts
+++ b/web/src/server/api/routers/comments.ts
@@ -10,122 +10,97 @@ import { Prisma, CreateCommentData, DeleteCommentData } from "@langfuse/shared";
import { auditLog } from "@/src/features/audit-logs/auditLog";
import { TRPCError } from "@trpc/server";
import { validateCommentReferenceObject } from "@/src/features/comments/validateCommentReferenceObject";
-import {
- getTracesIdentifierForSession,
- logger,
-} from "@langfuse/shared/src/server";
+import { getTracesIdentifierForSession } from "@langfuse/shared/src/server";
export const commentsRouter = createTRPCRouter({
create: protectedProjectProcedure
.input(CreateCommentData)
.mutation(async ({ input, ctx }) => {
- try {
- throwIfNoProjectAccess({
- session: ctx.session,
- projectId: input.projectId,
- scope: "comments:CUD",
- });
-
- const result = await validateCommentReferenceObject({
- ctx,
- input,
- });
-
- if (result.errorMessage) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: result.errorMessage,
- });
- }
-
- const comment = await ctx.prisma.comment.create({
- data: {
- projectId: input.projectId,
- content: input.content,
- objectId: input.objectId,
- objectType: input.objectType,
- authorUserId: ctx.session.user.id,
- },
- });
-
- await auditLog({
- session: ctx.session,
- resourceType: "comment",
- resourceId: comment.id,
- action: "create",
- after: comment,
- });
-
- return comment;
- } catch (error) {
- logger.error("Failed to call comments.create", error);
- if (error instanceof TRPCError) {
- throw error;
- }
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "comments:CUD",
+ });
+
+ const result = await validateCommentReferenceObject({
+ ctx,
+ input,
+ });
+
+ if (result.errorMessage) {
throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Creating comment failed.",
+ code: "NOT_FOUND",
+ message: result.errorMessage,
});
}
+
+ const comment = await ctx.prisma.comment.create({
+ data: {
+ projectId: input.projectId,
+ content: input.content,
+ objectId: input.objectId,
+ objectType: input.objectType,
+ authorUserId: ctx.session.user.id,
+ },
+ });
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "comment",
+ resourceId: comment.id,
+ action: "create",
+ after: comment,
+ });
+
+ return comment;
}),
delete: protectedProjectProcedure
.input(DeleteCommentData)
.mutation(async ({ input, ctx }) => {
- try {
- throwIfNoProjectAccess({
- session: ctx.session,
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "comments:CUD",
+ });
+
+ const comment = await ctx.prisma.comment.findFirst({
+ where: {
+ id: input.commentId,
projectId: input.projectId,
- scope: "comments:CUD",
- });
-
- const comment = await ctx.prisma.comment.findFirst({
- where: {
- id: input.commentId,
- projectId: input.projectId,
- objectId: input.objectId,
- objectType: input.objectType,
- },
- });
- if (!comment) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "No comment with this id in this project.",
- });
- }
-
- if (comment.authorUserId !== ctx.session.user.id) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Comment author user id does not match provided user id",
- });
- }
-
- await ctx.prisma.comment.delete({
- where: {
- id: comment.id,
- projectId: comment.projectId,
- objectId: comment.objectId,
- objectType: comment.objectType,
- },
+ objectId: input.objectId,
+ objectType: input.objectType,
+ },
+ });
+ if (!comment) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "No comment with this id in this project.",
});
+ }
- await auditLog({
- session: ctx.session,
- resourceType: "comment",
- resourceId: comment.id,
- action: "delete",
- before: comment,
- });
- } catch (error) {
- logger.error("Failed to call comments.delete", error);
- if (error instanceof TRPCError) {
- throw error;
- }
+ if (comment.authorUserId !== ctx.session.user.id) {
throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Deleting comment failed.",
+ code: "NOT_FOUND",
+ message: "Comment author user id does not match provided user id",
});
}
+
+ await ctx.prisma.comment.delete({
+ where: {
+ id: comment.id,
+ projectId: comment.projectId,
+ objectId: comment.objectId,
+ objectType: comment.objectType,
+ },
+ });
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "comment",
+ resourceId: comment.id,
+ action: "delete",
+ before: comment,
+ });
}),
getByObjectId: protectedProjectProcedure
.input(
@@ -136,24 +111,23 @@ export const commentsRouter = createTRPCRouter({
}),
)
.query(async ({ input, ctx }) => {
- try {
- throwIfNoProjectAccess({
- session: ctx.session,
- projectId: input.projectId,
- scope: "comments:read",
- });
-
- const comments = await ctx.prisma.$queryRaw<
- Array<{
- id: string;
- content: string;
- createdAt: Date;
- authorUserId: string | null;
- authorUserImage: string | null;
- authorUserName: string | null;
- }>
- >(
- Prisma.sql`
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "comments:read",
+ });
+
+ const comments = await ctx.prisma.$queryRaw<
+ Array<{
+ id: string;
+ content: string;
+ createdAt: Date;
+ authorUserId: string | null;
+ authorUserImage: string | null;
+ authorUserName: string | null;
+ }>
+ >(
+ Prisma.sql`
SELECT
c.id,
c.content,
@@ -170,19 +144,9 @@ export const commentsRouter = createTRPCRouter({
ORDER BY
c.created_at DESC
`,
- );
+ );
- return comments;
- } catch (error) {
- logger.error("Failed to call comments.getByObjectId", error);
- if (error instanceof TRPCError) {
- throw error;
- }
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Fetching comments by object id failed.",
- });
- }
+ return comments;
}),
getCountByObjectId: protectedProjectProcedure
.input(
@@ -193,31 +157,20 @@ export const commentsRouter = createTRPCRouter({
}),
)
.query(async ({ input, ctx }) => {
- try {
- throwIfNoProjectAccess({
- session: ctx.session,
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "comments:read",
+ });
+
+ const commentCount = await ctx.prisma.comment.count({
+ where: {
projectId: input.projectId,
- scope: "comments:read",
- });
-
- const commentCount = await ctx.prisma.comment.count({
- where: {
- projectId: input.projectId,
- objectId: input.objectId,
- objectType: input.objectType,
- },
- });
- return new Map([[input.objectId, commentCount]]);
- } catch (error) {
- logger.error("Failed to call comments.getCountByObjectId", error);
- if (error instanceof TRPCError) {
- throw error;
- }
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Fetching comment count by object id failed.",
- });
- }
+ objectId: input.objectId,
+ objectType: input.objectType,
+ },
+ });
+ return new Map([[input.objectId, commentCount]]);
}),
getCountByObjectType: protectedProjectProcedure
.input(
@@ -227,41 +180,30 @@ export const commentsRouter = createTRPCRouter({
}),
)
.query(async ({ input, ctx }) => {
- try {
- throwIfNoProjectAccess({
- session: ctx.session,
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "comments:read",
+ });
+
+ // latency of query to be improved
+ const commentCounts = await ctx.prisma.comment.groupBy({
+ by: ["objectId"],
+ where: {
projectId: input.projectId,
- scope: "comments:read",
- });
-
- // latency of query to be improved
- const commentCounts = await ctx.prisma.comment.groupBy({
- by: ["objectId"],
- where: {
- projectId: input.projectId,
- objectType: input.objectType,
- },
- _count: {
- objectId: true,
- },
- });
-
- return new Map(
- commentCounts.map(({ objectId, _count }) => [
- objectId,
- _count.objectId,
- ]),
- );
- } catch (error) {
- logger.error("Failed to call comments.getCountByObjectType", error);
- if (error instanceof TRPCError) {
- throw error;
- }
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Fetching comment count by object type failed.",
- });
- }
+ objectType: input.objectType,
+ },
+ _count: {
+ objectId: true,
+ },
+ });
+
+ return new Map(
+ commentCounts.map(({ objectId, _count }) => [
+ objectId,
+ _count.objectId,
+ ]),
+ );
}),
getTraceCommentCountsBySessionId: protectedProjectProcedure
.input(
@@ -271,15 +213,14 @@ export const commentsRouter = createTRPCRouter({
}),
)
.query(async ({ input, ctx }) => {
- try {
- const clickhouseTraces = await getTracesIdentifierForSession(
- input.projectId,
- input.sessionId,
- );
-
- const allTraceCommentCounts = await ctx.prisma.$queryRaw<
- Array<{ objectId: string; count: bigint }>
- >`
+ const clickhouseTraces = await getTracesIdentifierForSession(
+ input.projectId,
+ input.sessionId,
+ );
+
+ const allTraceCommentCounts = await ctx.prisma.$queryRaw<
+ Array<{ objectId: string; count: bigint }>
+ >`
SELECT object_id as "objectId", COUNT(*) as count
FROM comments
WHERE project_id = ${input.projectId}
@@ -287,21 +228,11 @@ export const commentsRouter = createTRPCRouter({
GROUP BY object_id
`;
- const traceIds = new Set(clickhouseTraces.map((t) => t.id));
- return new Map(
- allTraceCommentCounts
- .filter((c) => traceIds.has(c.objectId))
- .map(({ objectId, count }) => [objectId, Number(count)]),
- );
- } catch (error) {
- logger.error(
- "Failed to call comments.getTraceCommentCountBySessionId",
- error,
- );
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Unable to get trace comment counts by session id",
- });
- }
+ const traceIds = new Set(clickhouseTraces.map((t) => t.id));
+ return new Map(
+ allTraceCommentCounts
+ .filter((c) => traceIds.has(c.objectId))
+ .map(({ objectId, count }) => [objectId, Number(count)]),
+ );
}),
});
diff --git a/web/src/server/api/routers/media.ts b/web/src/server/api/routers/media.ts
index 6c5064d962..a7cf006ec3 100644
--- a/web/src/server/api/routers/media.ts
+++ b/web/src/server/api/routers/media.ts
@@ -6,7 +6,6 @@ import {
createTRPCRouter,
protectedProjectProcedure,
} from "@/src/server/api/trpc";
-import { logger } from "@langfuse/shared/src/server";
import { TRPCError } from "@trpc/server";
import {
type MediaContentType,
@@ -18,65 +17,50 @@ export const mediaRouter = createTRPCRouter({
getById: protectedProjectProcedure
.input(z.object({ mediaId: z.string(), projectId: z.string() }))
.query(async ({ input, ctx }) => {
- try {
- const { projectId, mediaId } = input;
+ const { projectId, mediaId } = input;
- const media = await ctx.prisma.media.findUnique({
- where: {
- projectId_id: {
- projectId,
- id: mediaId,
- },
+ const media = await ctx.prisma.media.findUnique({
+ where: {
+ projectId_id: {
+ projectId,
+ id: mediaId,
},
- });
+ },
+ });
- if (!media)
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Media asset not found",
- });
- if (!media.uploadHttpStatus)
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Media not yet uploaded",
- });
- if (!(media.uploadHttpStatus === 200 || media.uploadHttpStatus === 201))
- throw new TRPCError({
- code: "NOT_FOUND",
- message: `Media upload failed`,
- });
+ if (!media)
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Media asset not found",
+ });
+ if (!media.uploadHttpStatus)
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Media not yet uploaded",
+ });
+ if (!(media.uploadHttpStatus === 200 || media.uploadHttpStatus === 201))
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: `Media upload failed`,
+ });
- const mediaStorageClient = getMediaStorageServiceClient(
- media.bucketName,
- );
- const ttlSeconds = env.LANGFUSE_S3_MEDIA_DOWNLOAD_URL_EXPIRY_SECONDS;
- const urlExpiry = new Date(
- Date.now() + ttlSeconds * 1000,
- ).toISOString();
+ const mediaStorageClient = getMediaStorageServiceClient(media.bucketName);
+ const ttlSeconds = env.LANGFUSE_S3_MEDIA_DOWNLOAD_URL_EXPIRY_SECONDS;
+ const urlExpiry = new Date(Date.now() + ttlSeconds * 1000).toISOString();
- const url = await mediaStorageClient.getSignedUrl(
- media.bucketPath,
- ttlSeconds,
- false,
- );
+ const url = await mediaStorageClient.getSignedUrl(
+ media.bucketPath,
+ ttlSeconds,
+ false,
+ );
- return {
- mediaId,
- contentType: media.contentType,
- contentLength: Number(media.contentLength),
- url,
- urlExpiry,
- };
- } catch (e) {
- logger.error(e);
- if (e instanceof TRPCError) {
- throw e;
- }
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Fetching media failed.",
- });
- }
+ return {
+ mediaId,
+ contentType: media.contentType,
+ contentLength: Number(media.contentLength),
+ url,
+ urlExpiry,
+ };
}),
getByTraceOrObservationId: protectedProjectProcedure
.input(
@@ -87,30 +71,29 @@ export const mediaRouter = createTRPCRouter({
}),
)
.query(async ({ input, ctx }) => {
- try {
- const { projectId, traceId } = input;
+ const { projectId, traceId } = input;
- let media: {
- id: string;
- field: MediaEnabledFields;
- bucket_name: string;
- bucket_path: string;
- content_type: string;
- content_length: bigint;
- }[] = [];
+ let media: {
+ id: string;
+ field: MediaEnabledFields;
+ bucket_name: string;
+ bucket_path: string;
+ content_type: string;
+ content_length: bigint;
+ }[] = [];
- if (!input.observationId) {
- // Get all media on the trace IO. This is NOT all media on the observations belonging to the trace.
- media = await ctx.prisma.$queryRaw<
- {
- id: string;
- field: MediaEnabledFields;
- bucket_name: string;
- bucket_path: string;
- content_type: string;
- content_length: bigint;
- }[]
- >`
+ if (!input.observationId) {
+ // Get all media on the trace IO. This is NOT all media on the observations belonging to the trace.
+ media = await ctx.prisma.$queryRaw<
+ {
+ id: string;
+ field: MediaEnabledFields;
+ bucket_name: string;
+ bucket_path: string;
+ content_type: string;
+ content_length: bigint;
+ }[]
+ >`
SELECT
tm.field,
m.id,
@@ -127,17 +110,17 @@ export const mediaRouter = createTRPCRouter({
tm.project_id = ${projectId}
AND tm.trace_id = ${traceId}
`;
- } else {
- media = await ctx.prisma.$queryRaw<
- {
- id: string;
- field: MediaEnabledFields;
- bucket_name: string;
- bucket_path: string;
- content_type: string;
- content_length: bigint;
- }[]
- >`
+ } else {
+ media = await ctx.prisma.$queryRaw<
+ {
+ id: string;
+ field: MediaEnabledFields;
+ bucket_name: string;
+ bucket_path: string;
+ content_type: string;
+ content_length: bigint;
+ }[]
+ >`
SELECT
om.field,
m.id,
@@ -155,47 +138,35 @@ export const mediaRouter = createTRPCRouter({
AND om.trace_id = ${traceId}
AND om.observation_id = ${input.observationId}
`;
- }
+ }
- if (!media.length) {
- return [];
- }
+ if (!media.length) {
+ return [];
+ }
- const mediaStorageClient = getMediaStorageServiceClient(
- media[0].bucket_name,
- );
- const ttlSeconds = env.LANGFUSE_S3_MEDIA_DOWNLOAD_URL_EXPIRY_SECONDS;
- const urlExpiry = new Date(
- Date.now() + ttlSeconds * 1000,
- ).toISOString();
+ const mediaStorageClient = getMediaStorageServiceClient(
+ media[0].bucket_name,
+ );
+ const ttlSeconds = env.LANGFUSE_S3_MEDIA_DOWNLOAD_URL_EXPIRY_SECONDS;
+ const urlExpiry = new Date(Date.now() + ttlSeconds * 1000).toISOString();
- // Use Promise.all as better to fail all media requests than one of them only
- return await Promise.all(
- media.map<Promise<MediaReturnType>>(async (m) => {
- const url = await mediaStorageClient.getSignedUrl(
- m.bucket_path,
- ttlSeconds,
- false,
- );
- return {
- mediaId: m.id,
- contentType: m.content_type as MediaContentType,
- contentLength: Number(m.content_length),
- field: m.field,
- url,
- urlExpiry,
- };
- }),
- );
- } catch (e) {
- logger.error(e);
- if (e instanceof TRPCError) {
- throw e;
- }
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Fetching media failed.",
- });
- }
+ // Use Promise.all as better to fail all media requests than one of them only
+ return await Promise.all(
+ media.map<Promise<MediaReturnType>>(async (m) => {
+ const url = await mediaStorageClient.getSignedUrl(
+ m.bucket_path,
+ ttlSeconds,
+ false,
+ );
+ return {
+ mediaId: m.id,
+ contentType: m.content_type as MediaContentType,
+ contentLength: Number(m.content_length),
+ field: m.field,
+ url,
+ urlExpiry,
+ };
+ }),
+ );
}),
});
diff --git a/web/src/server/api/routers/observations.ts b/web/src/server/api/routers/observations.ts
index 593c595e82..1d7c9999ae 100644
--- a/web/src/server/api/routers/observations.ts
+++ b/web/src/server/api/routers/observations.ts
@@ -8,7 +8,6 @@ import {
getObservationById,
getObservationByIdFromEventsTable,
} from "@langfuse/shared/src/server";
-import { TRPCError } from "@trpc/server";
import { z } from "zod/v4";
export const observationsRouter = createTRPCRouter({
@@ -23,43 +22,32 @@ export const observationsRouter = createTRPCRouter({
}),
)
.query(async ({ input }) => {
- try {
- const queryOpts = {
- id: input.observationId,
- projectId: input.projectId,
- fetchWithInputOutput: true,
- traceId: input.traceId,
- startTime: input.startTime ?? undefined,
- renderingProps: {
- truncated: input.truncated,
- shouldJsonParse: false,
- },
- };
- const obs =
- env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true"
- ? await getObservationByIdFromEventsTable(queryOpts)
- : await getObservationById(queryOpts);
- if (!obs) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Observation not found within authorized project",
- });
- }
- return {
- ...obs,
- input: obs.input as string,
- output: obs.output as string,
- metadata: obs.metadata != null ? JSON.stringify(obs.metadata) : null,
- internalModel: obs?.internalModelId,
- };
- } catch (e) {
- if (e instanceof LangfuseNotFoundError) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Observation not found within authorized project",
- });
- }
- throw e;
+ const queryOpts = {
+ id: input.observationId,
+ projectId: input.projectId,
+ fetchWithInputOutput: true,
+ traceId: input.traceId,
+ startTime: input.startTime ?? undefined,
+ renderingProps: {
+ truncated: input.truncated,
+ shouldJsonParse: false,
+ },
+ };
+ const obs =
+ env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true"
+ ? await getObservationByIdFromEventsTable(queryOpts)
+ : await getObservationById(queryOpts);
+ if (!obs) {
+ throw new LangfuseNotFoundError(
+ "Observation not found within authorized project",
+ );
}
+ return {
+ ...obs,
+ input: obs.input as string,
+ output: obs.output as string,
+ metadata: obs.metadata != null ? JSON.stringify(obs.metadata) : null,
+ internalModel: obs?.internalModelId,
+ };
}),
});
diff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.ts
index 982fd909c1..0e3c3999e8 100644
--- a/web/src/server/api/routers/sessions.ts
+++ b/web/src/server/api/routers/sessions.ts
@@ -137,85 +137,69 @@ export const sessionRouter = createTRPCRouter({
all: protectedProjectProcedure
.input(SessionFilterOptions)
.query(async ({ input, ctx }) => {
- try {
- const finalFilter = await getPublicSessionsFilter(
- input.projectId,
- input.filter ?? [],
- );
- const sessions = await getSessionsTable({
- projectId: input.projectId,
- filter: finalFilter,
- orderBy: input.orderBy,
- page: input.page,
- limit: input.limit,
- });
+ const finalFilter = await getPublicSessionsFilter(
+ input.projectId,
+ input.filter ?? [],
+ );
+ const sessions = await getSessionsTable({
+ projectId: input.projectId,
+ filter: finalFilter,
+ orderBy: input.orderBy,
+ page: input.page,
+ limit: input.limit,
+ });
- const prismaSessionInfo = await ctx.prisma.traceSession.findMany({
- where: {
- id: {
- in: sessions.map((s) => s.session_id),
- },
- projectId: input.projectId,
- },
- select: {
- id: true,
- bookmarked: true,
- public: true,
- environment: true,
+ const prismaSessionInfo = await ctx.prisma.traceSession.findMany({
+ where: {
+ id: {
+ in: sessions.map((s) => s.session_id),
},
- });
- return {
- sessions: sessions.map((s) => {
- return {
- id: s.session_id,
- userIds: s.user_ids,
- countTraces: s.trace_count,
- traceTags: s.trace_tags,
- createdAt: new Date(s.min_timestamp),
- bookmarked:
- prismaSessionInfo.find((p) => p.id === s.session_id)
- ?.bookmarked ?? false,
- public:
- prismaSessionInfo.find((p) => p.id === s.session_id)?.public ??
- false,
- environment: s.trace_environment,
- };
- }),
- };
- } catch (e) {
- logger.error("Unable to call sessions.all", e);
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "unable to get sessions",
- });
- }
+ projectId: input.projectId,
+ },
+ select: {
+ id: true,
+ bookmarked: true,
+ public: true,
+ environment: true,
+ },
+ });
+ return {
+ sessions: sessions.map((s) => {
+ return {
+ id: s.session_id,
+ userIds: s.user_ids,
+ countTraces: s.trace_count,
+ traceTags: s.trace_tags,
+ createdAt: new Date(s.min_timestamp),
+ bookmarked:
+ prismaSessionInfo.find((p) => p.id === s.session_id)
+ ?.bookmarked ?? false,
+ public:
+ prismaSessionInfo.find((p) => p.id === s.session_id)?.public ??
+ false,
+ environment: s.trace_environment,
+ };
+ }),
+ };
}),
countAll: protectedProjectProcedure
.input(SessionFilterOptions)
.query(async ({ input }) => {
- try {
- const finalFilter = await getPublicSessionsFilter(
- input.projectId,
- input.filter ?? [],
- );
- const count = await getSessionsTableCount({
- projectId: input.projectId,
- filter: finalFilter,
- orderBy: input.orderBy,
- page: 0,
- limit: 1,
- });
+ const finalFilter = await getPublicSessionsFilter(
+ input.projectId,
+ input.filter ?? [],
+ );
+ const count = await getSessionsTableCount({
+ projectId: input.projectId,
+ filter: finalFilter,
+ orderBy: input.orderBy,
+ page: 0,
+ limit: 1,
+ });
- return {
- totalCount: count,
- };
- } catch (e) {
- logger.error("Error in sessions.countAll", e);
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "unable to get session count",
- });
- }
+ return {
+ totalCount: count,
+ };
}),
metrics: protectedProjectProcedure
.input(
@@ -225,80 +209,71 @@ export const sessionRouter = createTRPCRouter({
}),
)
.query(async ({ input, ctx }) => {
- try {
- if (input.sessionIds.length === 0) return [];
- const finalFilter = await getPublicSessionsFilter(input.projectId, [
- {
- column: "id",
- type: "stringOptions",
- operator: "any of",
- value: input.sessionIds,
- },
- ]);
- const sessions = await getSessionsWithMetrics({
- projectId: input.projectId,
- filter: finalFilter,
- });
+ if (input.sessionIds.length === 0) return [];
+ const finalFilter = await getPublicSessionsFilter(input.projectId, [
+ {
+ column: "id",
+ type: "stringOptions",
+ operator: "any of",
+ value: input.sessionIds,
+ },
+ ]);
+ const sessions = await getSessionsWithMetrics({
+ projectId: input.projectId,
+ filter: finalFilter,
+ });
- const prismaSessionInfo = await ctx.prisma.traceSession.findMany({
- where: {
- id: {
- in: sessions.map((s) => s.session_id),
- },
- projectId: input.projectId,
- },
- select: {
- id: true,
- bookmarked: true,
- public: true,
+ const prismaSessionInfo = await ctx.prisma.traceSession.findMany({
+ where: {
+ id: {
+ in: sessions.map((s) => s.session_id),
},
- });
+ projectId: input.projectId,
+ },
+ select: {
+ id: true,
+ bookmarked: true,
+ public: true,
+ },
+ });
- const scores = await getScoresForSessions({
- projectId: ctx.session.projectId,
- sessionIds: sessions.map((s) => s.session_id),
- limit: 1000,
- offset: 0,
- });
+ const scores = await getScoresForSessions({
+ projectId: ctx.session.projectId,
+ sessionIds: sessions.map((s) => s.session_id),
+ limit: 1000,
+ offset: 0,
+ });
- const validatedScores = filterAndValidateDbScoreList({
- scores,
- onParseError: traceException,
- });
+ const validatedScores = filterAndValidateDbScoreList({
+ scores,
+ onParseError: traceException,
+ });
- return sessions.map((s) => ({
- id: s.session_id,
- userIds: s.user_ids,
- countTraces: s.trace_count,
- traceTags: s.trace_tags,
- createdAt: new Date(s.min_timestamp),
- bookmarked:
- prismaSessionInfo.find((p) => p.id === s.session_id)?.bookmarked ??
- false,
- public:
- prismaSessionInfo.find((p) => p.id === s.session_id)?.public ??
- false,
- environment: s.trace_environment,
- trace_count: Number(s.trace_count),
- total_observations: Number(s.total_observations),
- sessionDuration: Number(s.duration),
- inputCost: new Decimal(s.session_input_cost),
- outputCost: new Decimal(s.session_output_cost),
- totalCost: new Decimal(s.session_total_cost),
- promptTokens: Number(s.session_input_usage),
- completionTokens: Number(s.session_output_usage),
- totalTokens: Number(s.session_total_usage),
- scores: aggregateScores(
- validatedScores.filter((score) => score.sessionId === s.session_id),
- ),
- }));
- } catch (e) {
- logger.error("Error in sessions.metrics", e);
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "unable to get session metrics",
- });
- }
+ return sessions.map((s) => ({
+ id: s.session_id,
+ userIds: s.user_ids,
+ countTraces: s.trace_count,
+ traceTags: s.trace_tags,
+ createdAt: new Date(s.min_timestamp),
+ bookmarked:
+ prismaSessionInfo.find((p) => p.id === s.session_id)?.bookmarked ??
+ false,
+ public:
+ prismaSessionInfo.find((p) => p.id === s.session_id)?.public ?? false,
+ environment: s.trace_environment,
+ trace_count: Number(s.trace_count),
+ total_observations: Number(s.total_observations),
+ sessionDuration: Number(s.duration),
+ inputCost: new Decimal(s.session_input_cost),
+ outputCost: new Decimal(s.session_output_cost),
+ totalCost: new Decimal(s.session_total_cost),
+ promptTokens: Number(s.session_input_usage),
+ completionTokens: Number(s.session_output_usage),
+ totalTokens: Number(s.session_total_usage),
+ scores: aggregateScores(
+ validatedScores.filter((score) => score.sessionId === s.session_id),
+ ),
+ }));
}),
filterOptions: protectedProjectProcedure
.input(
@@ -308,78 +283,70 @@ export const sessionRouter = createTRPCRouter({
}),
)
.query(async ({ input }): Promise<SessionOptions> => {
- try {
- const { timestampFilter } = input;
- const columns = [
- ...tracesTableUiColumnDefinitions,
- {
- uiTableName: "Created At",
- uiTableId: "createdAt",
- clickhouseTableName: "traces",
- clickhouseSelect: "timestamp",
- },
- ];
- const filter: FilterState = [
- {
- column: "sessionId",
- operator: "is not null",
- type: "null",
- value: "",
- },
- ];
- if (timestampFilter) {
- filter.push(timestampFilter);
- }
- // Create a proper trace timestamp filter for score functions
- const scoreTimestampFilter = timestampFilter
- ? {
- ...timestampFilter,
- column: "Timestamp", // Use exact trace column name for score functions
- }
- : null;
+ const { timestampFilter } = input;
+ const columns = [
+ ...tracesTableUiColumnDefinitions,
+ {
+ uiTableName: "Created At",
+ uiTableId: "createdAt",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "timestamp",
+ },
+ ];
+ const filter: FilterState = [
+ {
+ column: "sessionId",
+ operator: "is not null",
+ type: "null",
+ value: "",
+ },
+ ];
+ if (timestampFilter) {
+ filter.push(timestampFilter);
+ }
+ // Create a proper trace timestamp filter for score functions
+ const scoreTimestampFilter = timestampFilter
+ ? {
+ ...timestampFilter,
+ column: "Timestamp", // Use exact trace column name for score functions
+ }
+ : null;
- const [userIds, tags, numericScoreNames, categoricalScoreNames] =
- await Promise.all([
- getTracesGroupedByUsers(
- input.projectId,
- filter,
- undefined,
- 1000,
- 0,
- columns,
- ),
- getTracesGroupedByTags({
- projectId: input.projectId,
- filter,
- columns,
- }),
- getNumericScoresGroupedByName(
- input.projectId,
- scoreTimestampFilter ? [scoreTimestampFilter] : [],
- ),
- getCategoricalScoresGroupedByName(
- input.projectId,
- scoreTimestampFilter ? [scoreTimestampFilter] : [],
- ),
- ]);
+ const [userIds, tags, numericScoreNames, categoricalScoreNames] =
+ await Promise.all([
+ getTracesGroupedByUsers(
+ input.projectId,
+ filter,
+ undefined,
+ 1000,
+ 0,
+ columns,
+ ),
+ getTracesGroupedByTags({
+ projectId: input.projectId,
+ filter,
+ columns,
+ }),
+ getNumericScoresGroupedByName(
+ input.projectId,
+ scoreTimestampFilter ? [scoreTimestampFilter] : [],
+ ),
+ getCategoricalScoresGroupedByName(
+ input.projectId,
+ scoreTimestampFilter ? [scoreTimestampFilter] : [],
+ ),
+ ]);
- return {
- userIds: userIds.map((row) => ({
- value: row.user,
- count: Number(row.count),
- })),
- environment: [], // Environment is fetched separately via api.projects.environmentFilterOptions
- tags: tags,
- scores_avg: numericScoreNames.map((s) => s.name),
- score_categories: categoricalScoreNames,
- };
- } catch (e) {
- logger.error("Unable to get sessions.filterOptions", e);
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "unable to get session filter options",
- });
- }
+ return {
+ userIds: userIds.map((row) => ({
+ value: row.user,
+ count: Number(row.count),
+ })),
+ environment: [], // Environment is fetched separately via api.projects.environmentFilterOptions
+ tags: tags,
+ scores_avg: numericScoreNames.map((s) => s.name),
+ score_categories: categoricalScoreNames,
+ };
}),
byIdWithScores: protectedGetSessionProcedure
.input(
@@ -473,36 +440,28 @@ export const sessionRouter = createTRPCRouter({
}),
)
.mutation(async ({ input, ctx }) => {
- try {
- throwIfNoProjectAccess({
- session: ctx.session,
- projectId: input.projectId,
- scope: "objects:publish",
- });
- await auditLog({
- session: ctx.session,
- resourceType: "session",
- resourceId: input.sessionId,
- action: "publish",
- after: input.public,
- });
- return ctx.prisma.traceSession.update({
- where: {
- id_projectId: {
- id: input.sessionId,
- projectId: input.projectId,
- },
- },
- data: {
- public: input.public,
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "objects:publish",
+ });
+ await auditLog({
+ session: ctx.session,
+ resourceType: "session",
+ resourceId: input.sessionId,
+ action: "publish",
+ after: input.public,
+ });
+ return ctx.prisma.traceSession.update({
+ where: {
+ id_projectId: {
+ id: input.sessionId,
+ projectId: input.projectId,
},
- });
- } catch (e) {
- logger.error("Unable to call sessions.publish", e);
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "unable to publish session",
- });
- }
+ },
+ data: {
+ public: input.public,
+ },
+ });
}),
});
diff --git a/web/src/server/api/routers/tableViewPresets.ts b/web/src/server/api/routers/tableViewPresets.ts
index f1499aa883..fcf4be63ae 100644
--- a/web/src/server/api/routers/tableViewPresets.ts
+++ b/web/src/server/api/routers/tableViewPresets.ts
@@ -10,39 +10,7 @@ import {
UpdateTableViewPresetsInput,
UpdateTableViewPresetsNameInput,
} from "@langfuse/shared/src/server";
-import { TRPCError } from "@trpc/server";
-import {
- LangfuseNotFoundError,
- TableViewPresetTableName,
-} from "@langfuse/shared";
-
-/**
- * Maps domain errors to appropriate TRPC errors
- * @param fn Function to execute that might throw domain errors
- * @param errorConfig Optional configuration for customizing error messages
- */
-export async function withErrorMapping<T>(
- fn: () => Promise<T>,
- errorConfig?: {
- notFoundMessage?: string;
- },
-): Promise<T> {
- try {
- return await fn();
- } catch (error) {
- // Map domain errors to TRPC errors
- if (error instanceof LangfuseNotFoundError) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: errorConfig?.notFoundMessage || error.message,
- cause: error,
- });
- }
-
- // Re-throw unknown errors
- throw error;
- }
-}
+import { TableViewPresetTableName } from "@langfuse/shared";
export const TableViewPresetsRouter = createTRPCRouter({
create: protectedProjectProcedure
@@ -74,13 +42,9 @@ export const TableViewPresetsRouter = createTRPCRouter({
scope: "TableViewPresets:CUD",
});
- const view = await withErrorMapping(
- () =>
- TableViewService.updateTableViewPresets(input, ctx.session.user?.id),
- {
- notFoundMessage:
- "Saved table view preset not found, failed to update",
- },
+ const view = await TableViewService.updateTableViewPresets(
+ input,
+ ctx.session.user?.id,
);
return {
@@ -98,16 +62,9 @@ export const TableViewPresetsRouter = createTRPCRouter({
scope: "TableViewPresets:CUD",
});
- const view = await withErrorMapping(
- () =>
- TableViewService.updateTableViewPresetsName(
- input,
- ctx.session.user?.id,
- ),
- {
- notFoundMessage:
- "Saved table view preset not found, failed to update name",
- },
+ const view = await TableViewService.updateTableViewPresetsName(
+ input,
+ ctx.session.user?.id,
);
return {
@@ -169,16 +126,9 @@ export const TableViewPresetsRouter = createTRPCRouter({
scope: "TableViewPresets:read",
});
- return await withErrorMapping(
- () =>
- TableViewService.getTableViewPresetsById(
- input.viewId,
- input.projectId,
- ),
- {
- notFoundMessage:
- "Saved table view preset not found, likely it has been deleted",
- },
+ return await TableViewService.getTableViewPresetsById(
+ input.viewId,
+ input.projectId,
);
}),
diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.ts
index 13c283121c..7934c0459b 100644
--- a/web/src/server/api/trpc.ts
+++ b/web/src/server/api/trpc.ts
@@ -138,23 +138,19 @@ const resolveError = (error: TRPCError) => {
return { code: error.code, httpStatus: getHTTPStatusCodeFromError(error) };
};
+const logErrorByCode = (errorCode: TRPCError["code"]) => {
+ if (errorCode === "NOT_FOUND" || errorCode === "UNAUTHORIZED") {
+ logger.info(`middleware intercepted error with code ${errorCode}`);
+ } else {
+ logger.error(`middleware intercepted error with code ${errorCode}`);
+ }
+};
+
// global error handling
const withErrorHandling = t.middleware(async ({ ctx, next }) => {
const res = await next({ ctx }); // pass the context to the next middleware
if (!res.ok) {
- if (res.error.code === "NOT_FOUND" || res.error.code === "UNAUTHORIZED") {
- logger.info(
- `middleware intercepted error with code ${res.error.code}`,
- res.error,
- );
- } else {
- logger.error(
- `middleware intercepted error with code ${res.error.code}`,
- res.error,
- );
- }
-
if (res.error.cause instanceof ClickHouseResourceError) {
// Surface ClickHouse errors using an advice message
// which is supposed to provide a bit of guidance to the user.
@@ -162,6 +158,7 @@ const withErrorHandling = t.middleware(async ({ ctx, next }) => {
code: "SERVICE_UNAVAILABLE",
message: ClickHouseResourceError.ERROR_ADVICE_MESSAGE,
});
+ logErrorByCode(res.error.code);
} else {
// Throw a new TRPC error with:
// - The same error code as the original error
@@ -179,6 +176,7 @@ const withErrorHandling = t.middleware(async ({ ctx, next }) => {
? res.error.message
: "Internal error. " + errorMessage,
});
+ logErrorByCode(code);
}
}