Skip to content

Commit 8a9eb1c

Browse files
committed
address council comments
1 parent 0710e62 commit 8a9eb1c

7 files changed

Lines changed: 67 additions & 60 deletions

File tree

apps/sim/app/api/memory/route.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
233233

234234
logger.error(`[${requestId}] Error creating memory`, { error })
235235
return NextResponse.json(
236-
{ success: false, error: { message: error.message || 'Failed to create memory' } },
236+
{ success: false, error: { message: 'Failed to create memory' } },
237237
{ status: 500 }
238238
)
239239
}

apps/sim/app/api/webhooks/agentmail/route.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,10 @@ export const POST = withRouteHandler(async (req: Request) => {
7878
workspaceId: result.id,
7979
issues: envelopeResult.error.issues,
8080
})
81-
return NextResponse.json({ ok: true })
81+
return NextResponse.json(
82+
{ error: 'Invalid envelope payload', details: envelopeResult.error.issues },
83+
{ status: 400 }
84+
)
8285
}
8386

8487
if (envelopeResult.data.event_type !== 'message.received') {
@@ -91,7 +94,10 @@ export const POST = withRouteHandler(async (req: Request) => {
9194
workspaceId: result.id,
9295
issues: messageResult.error.issues,
9396
})
94-
return NextResponse.json({ ok: true })
97+
return NextResponse.json(
98+
{ error: 'Invalid message payload', details: messageResult.error.issues },
99+
{ status: 400 }
100+
)
95101
}
96102

97103
const message: AgentMailWebhookPayload['message'] = messageResult.data

apps/sim/app/api/webhooks/poll/[provider]/route.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,17 @@ export const maxDuration = 180
1818

1919
export const GET = withRouteHandler(
2020
async (request: NextRequest, context: { params: Promise<{ provider: string }> }) => {
21-
const parsed = await parseRequest(webhookPollingContract, request, context)
22-
if (!parsed.success) return parsed.response
23-
const { provider } = parsed.data.params
2421
const requestId = generateShortId()
22+
let provider: string | undefined
2523

2624
try {
27-
const authError = verifyCronAuth(request, `${provider} webhook polling`)
25+
const authError = verifyCronAuth(request, 'webhook polling')
2826
if (authError) return authError
2927

28+
const parsed = await parseRequest(webhookPollingContract, request, context)
29+
if (!parsed.success) return parsed.response
30+
provider = parsed.data.params.provider
31+
3032
if (!VALID_POLLING_PROVIDERS.has(provider)) {
3133
return NextResponse.json(
3234
{ error: `Unknown polling provider: ${provider}` },
@@ -67,11 +69,12 @@ export const GET = withRouteHandler(
6769
}
6870
}
6971
} catch (error) {
70-
logger.error(`Error during ${provider} polling (${requestId}):`, error)
72+
const providerLabel = provider ?? 'webhook'
73+
logger.error(`Error during ${providerLabel} polling (${requestId}):`, error)
7174
return NextResponse.json(
7275
{
7376
success: false,
74-
message: `${provider} polling failed`,
77+
message: `${providerLabel} polling failed`,
7578
error: error instanceof Error ? error.message : 'Unknown error',
7679
requestId,
7780
},

apps/sim/app/api/webhooks/trigger/[path]/route.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ export const GET = withRouteHandler(
2929
async (request: NextRequest, context: { params: Promise<{ path: string }> }) => {
3030
const requestId = generateRequestId()
3131
const parsed = await parseRequest(webhookTriggerGetContract, request, context)
32-
if (!parsed.success) return new NextResponse('Not Found', { status: 404 })
32+
if (!parsed.success) return parsed.response
3333
const { path } = parsed.data.params
3434

3535
// Handle provider-specific GET verifications (Microsoft Graph, WhatsApp, etc.)
@@ -66,7 +66,7 @@ async function handleWebhookPost(
6666
): Promise<NextResponse> {
6767
const requestId = generateRequestId()
6868
const parsed = await parseRequest(webhookTriggerPostContract, request, context)
69-
if (!parsed.success) return new NextResponse('Not Found', { status: 404 })
69+
if (!parsed.success) return parsed.response
7070
const { path } = parsed.data.params
7171

7272
const earlyChallenge = await handleProviderChallenges({}, request, requestId, path)

apps/sim/app/api/workflows/[id]/execute/route.ts

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -211,10 +211,7 @@ async function handleAsyncExecution(params: AsyncExecutionParams): Promise<NextR
211211
)
212212
} catch (error: any) {
213213
asyncLogger.error('Failed to queue async execution', error)
214-
return NextResponse.json(
215-
{ error: `Failed to queue async execution: ${error.message}` },
216-
{ status: 500 }
217-
)
214+
return NextResponse.json({ error: 'Failed to queue async execution' }, { status: 500 })
218215
}
219216
}
220217

@@ -304,13 +301,14 @@ async function handleExecutePost(
304301
}
305302

306303
let body: any = {}
307-
try {
308-
const text = await req.text()
309-
if (text) {
304+
const text = await req.text()
305+
if (text) {
306+
try {
310307
body = JSON.parse(text)
308+
} catch (error) {
309+
reqLogger.warn('Failed to parse request body', { error: toError(error).message })
310+
return NextResponse.json({ error: 'Invalid JSON in request body' }, { status: 400 })
311311
}
312-
} catch (error) {
313-
reqLogger.warn('Failed to parse request body, using defaults')
314312
}
315313

316314
const validation = executeWorkflowBodySchema.safeParse(body)

apps/sim/app/api/workflows/route.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
102102
} catch (error: any) {
103103
const elapsed = Date.now() - startTime
104104
logger.error(`[${requestId}] Workflow fetch error after ${elapsed}ms`, error)
105-
return NextResponse.json({ error: error.message }, { status: 500 })
105+
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
106106
}
107107
})
108108

apps/sim/app/workspace/[workspaceId]/knowledge/hooks/use-knowledge-upload.ts

Lines changed: 39 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,36 @@ class ProcessingError extends KnowledgeUploadError {
8484
}
8585
}
8686

87+
/**
88+
* Reads a failed `Response`'s JSON body and produces a user-facing error
89+
* string that combines the top-level `error`/`message` with any Zod
90+
* `details[].message` entries. Falls back to `statusText` then status code
91+
* when the body is unreadable.
92+
*/
93+
async function readResponseError(
94+
response: Response,
95+
fallback = 'Unknown error'
96+
): Promise<{ message: string; body: any }> {
97+
let body: any = null
98+
try {
99+
body = await response.json()
100+
} catch {
101+
body = null
102+
}
103+
const base =
104+
body?.error || body?.message || response.statusText || `HTTP ${response.status}` || fallback
105+
const detailMessages = Array.isArray(body?.details)
106+
? body.details
107+
.map((d: any) => (typeof d?.message === 'string' ? d.message : null))
108+
.filter((m: string | null): m is string => Boolean(m))
109+
.join(', ')
110+
: ''
111+
return {
112+
message: detailMessages ? `${base}: ${detailMessages}` : base,
113+
body,
114+
}
115+
}
116+
87117
/**
88118
* Configuration constants for file upload operations
89119
*/
@@ -293,22 +323,12 @@ const getPresignedData = async (
293323
})
294324

295325
if (!presignedResponse.ok) {
296-
let errorDetails: any = null
297-
try {
298-
errorDetails = await presignedResponse.json()
299-
} catch {
300-
errorDetails = null
301-
}
302-
326+
const { message, body } = await readResponseError(presignedResponse)
303327
logger.error('Presigned URL request failed', {
304328
status: presignedResponse.status,
305329
fileSize: file.size,
306330
})
307-
308-
throw new PresignedUrlError(
309-
`Failed to get presigned URL for ${file.name}: ${presignedResponse.status} ${presignedResponse.statusText}`,
310-
errorDetails
311-
)
331+
throw new PresignedUrlError(`Failed to get presigned URL for ${file.name}: ${message}`, body)
312332
}
313333

314334
const presignedData = await presignedResponse.json()
@@ -786,17 +806,8 @@ export function useKnowledgeUpload(options: UseKnowledgeUploadOptions = {}) {
786806
})
787807

788808
if (!uploadResponse.ok) {
789-
let errorData: any = null
790-
try {
791-
errorData = await uploadResponse.json()
792-
} catch {
793-
errorData = null
794-
}
795-
796-
throw new DirectUploadError(
797-
`Failed to upload ${file.name}: ${errorData?.message || errorData?.error || 'Unknown error'}`,
798-
errorData
799-
)
809+
const { message, body } = await readResponseError(uploadResponse)
810+
throw new DirectUploadError(`Failed to upload ${file.name}: ${message}`, body)
800811
}
801812

802813
const uploadResult = await uploadResponse.json()
@@ -878,9 +889,8 @@ export function useKnowledgeUpload(options: UseKnowledgeUploadOptions = {}) {
878889
})
879890

880891
if (!batchResponse.ok) {
881-
throw new Error(
882-
`Batch ${batchIndex + 1} presigned URL generation failed: ${batchResponse.statusText}`
883-
)
892+
const { message } = await readResponseError(batchResponse)
893+
throw new Error(`Batch ${batchIndex + 1} presigned URL generation failed: ${message}`)
884894
}
885895

886896
const { files: presignedData } = await batchResponse.json()
@@ -1022,28 +1032,18 @@ export function useKnowledgeUpload(options: UseKnowledgeUploadOptions = {}) {
10221032
})
10231033

10241034
if (!processResponse.ok) {
1025-
let errorData: any = null
1026-
try {
1027-
errorData = await processResponse.json()
1028-
} catch {
1029-
errorData = null
1030-
}
1031-
1035+
const { message, body } = await readResponseError(processResponse)
10321036
logger.error('Document processing failed:', {
10331037
status: processResponse.status,
1034-
error: errorData,
1038+
error: body,
10351039
uploadedFiles: uploadedFiles.map((f) => ({
10361040
filename: f.filename,
10371041
fileUrl: f.fileUrl,
10381042
fileSize: f.fileSize,
10391043
mimeType: f.mimeType,
10401044
})),
10411045
})
1042-
1043-
throw new ProcessingError(
1044-
`Failed to start document processing: ${errorData?.error || errorData?.message || 'Unknown error'}`,
1045-
errorData
1046-
)
1046+
throw new ProcessingError(`Failed to start document processing: ${message}`, body)
10471047
}
10481048

10491049
const processResult = await processResponse.json()

0 commit comments

Comments
 (0)