diff --git a/packages/server/src/controllers/apikey/index.ts b/packages/server/src/controllers/apikey/index.ts index c35a69f8..1a2ad3af 100644 --- a/packages/server/src/controllers/apikey/index.ts +++ b/packages/server/src/controllers/apikey/index.ts @@ -1,6 +1,6 @@ import { Request, Response, NextFunction } from 'express' import { StatusCodes } from 'http-status-codes' -import { ApiError } from '../../errors/apiError' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' import apikeyService from '../../services/apikey' // Get api keys @@ -15,8 +15,8 @@ const getAllApiKeys = async (req: Request, res: Response, next: NextFunction) => const createApiKey = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.body.keyName === 'undefined' || req.body.keyName === '') { - throw new ApiError(StatusCodes.PRECONDITION_FAILED, `Error: apikeyController.createApiKey - keyName not provided!`) + if (typeof req.body === 'undefined' || !req.body.keyName) { + throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, `Error: apikeyController.createApiKey - keyName not provided!`) } const apiResponse = await apikeyService.createApiKey(req.body.keyName) return res.json(apiResponse) @@ -28,11 +28,11 @@ const createApiKey = async (req: Request, res: Response, next: NextFunction) => // Update api key const updateApiKey = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - new ApiError(StatusCodes.PRECONDITION_FAILED, `Error: apikeyController.updateApiKey - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, `Error: apikeyController.updateApiKey - id not provided!`) } - if (typeof req.body.keyName === 'undefined' || req.body.keyName === '') { - new ApiError(StatusCodes.PRECONDITION_FAILED, `Error: apikeyController.updateApiKey - keyName not provided!`) + if (typeof req.body === 'undefined' || !req.body.keyName) { + throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, `Error: apikeyController.updateApiKey - keyName not provided!`) } const apiResponse = await apikeyService.updateApiKey(req.params.id, req.body.keyName) return res.json(apiResponse) @@ -44,8 +44,8 @@ const updateApiKey = async (req: Request, res: Response, next: NextFunction) => // Delete api key const deleteApiKey = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - new ApiError(StatusCodes.PRECONDITION_FAILED, `Error: apikeyController.deleteApiKey - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, `Error: apikeyController.deleteApiKey - id not provided!`) } const apiResponse = await apikeyService.deleteApiKey(req.params.id) return res.json(apiResponse) @@ -57,13 +57,10 @@ const deleteApiKey = async (req: Request, res: Response, next: NextFunction) => // Verify api key const verifyApiKey = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.apiKey === 'undefined' || req.params.apiKey === '') { - new ApiError(StatusCodes.PRECONDITION_FAILED, `Error: apikeyController.verifyApiKey - apiKey not provided!`) + if (typeof req.params === 'undefined' || !req.params.apiKey) { + throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, `Error: apikeyController.verifyApiKey - apiKey not provided!`) } const apiResponse = await apikeyService.verifyApiKey(req.params.apiKey) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) diff --git a/packages/server/src/controllers/assistants/index.ts b/packages/server/src/controllers/assistants/index.ts index eed00752..c252dc56 100644 --- a/packages/server/src/controllers/assistants/index.ts +++ b/packages/server/src/controllers/assistants/index.ts @@ -1,15 +1,17 @@ import { Request, Response, NextFunction } from 'express' import assistantsService from '../../services/assistants' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { StatusCodes } from 'http-status-codes' -const creatAssistant = async (req: Request, res: Response, next: NextFunction) => { +const createAssistant = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.body === 'undefined' || req.body === '') { - throw new Error(`Error: assistantsController.creatAssistant - body not provided!`) - } - const apiResponse = await assistantsService.creatAssistant(req.body) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) + if (!req.body) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: assistantsController.createAssistant - body not provided!` + ) } + const apiResponse = await assistantsService.createAssistant(req.body) return res.json(apiResponse) } catch (error) { next(error) @@ -18,13 +20,13 @@ const creatAssistant = async (req: Request, res: Response, next: NextFunction) = const deleteAssistant = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: assistantsController.deleteAssistant - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: assistantsController.deleteAssistant - id not provided!` + ) } const apiResponse = await assistantsService.deleteAssistant(req.params.id, req.query.isDeleteBoth) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) @@ -34,9 +36,6 @@ const deleteAssistant = async (req: Request, res: Response, next: NextFunction) const getAllAssistants = async (req: Request, res: Response, next: NextFunction) => { try { const apiResponse = await assistantsService.getAllAssistants() - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) @@ -45,13 +44,13 @@ const getAllAssistants = async (req: Request, res: Response, next: NextFunction) const getAssistantById = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: assistantsController.getAssistantById - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: assistantsController.getAssistantById - id not provided!` + ) } const apiResponse = await assistantsService.getAssistantById(req.params.id) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) @@ -60,16 +59,19 @@ const getAssistantById = async (req: Request, res: Response, next: NextFunction) const updateAssistant = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: assistantsController.updateAssistant - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: assistantsController.updateAssistant - id not provided!` + ) } - if (typeof req.body === 'undefined' || req.body === '') { - throw new Error(`Error: assistantsController.updateAssistant - body not provided!`) + if (!req.body) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: assistantsController.updateAssistant - body not provided!` + ) } const apiResponse = await assistantsService.updateAssistant(req.params.id, req.body) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) @@ -77,7 +79,7 @@ const updateAssistant = async (req: Request, res: Response, next: NextFunction) } export default { - creatAssistant, + createAssistant, deleteAssistant, getAllAssistants, getAssistantById, diff --git a/packages/server/src/controllers/chat-messages/index.ts b/packages/server/src/controllers/chat-messages/index.ts index 02562b3a..7c32fb4c 100644 --- a/packages/server/src/controllers/chat-messages/index.ts +++ b/packages/server/src/controllers/chat-messages/index.ts @@ -6,11 +6,16 @@ import { clearSessionMemory } from '../../utils' import { getRunningExpressApp } from '../../utils/getRunningExpressApp' import { FindOptionsWhere } from 'typeorm' import { ChatMessage } from '../../database/entities/ChatMessage' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { StatusCodes } from 'http-status-codes' const createChatMessage = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.body === 'undefined' || req.body === '') { - throw new Error('Error: chatMessagesController.createChatMessage - request body not provided!') + if (!req.body) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + 'Error: chatMessagesController.createChatMessage - request body not provided!' + ) } const apiResponse = await chatMessagesService.createChatMessage(req.body) return res.json(apiResponse) @@ -44,8 +49,11 @@ const getAllChatMessages = async (req: Request, res: Response, next: NextFunctio const startDate = req.query?.startDate as string | undefined const endDate = req.query?.endDate as string | undefined const feedback = req.query?.feedback as boolean | undefined - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: chatMessageController.getAllChatMessages - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: chatMessageController.getAllChatMessages - id not provided!` + ) } const apiResponse = await chatMessagesService.getAllChatMessages( req.params.id, @@ -59,9 +67,6 @@ const getAllChatMessages = async (req: Request, res: Response, next: NextFunctio messageId, feedback ) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) @@ -90,9 +95,6 @@ const getAllInternalChatMessages = async (req: Request, res: Response, next: Nex messageId, feedback ) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) @@ -103,8 +105,11 @@ const getAllInternalChatMessages = async (req: Request, res: Response, next: Nex const removeAllChatMessages = async (req: Request, res: Response, next: NextFunction) => { try { const appServer = getRunningExpressApp() - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error('Error: chatMessagesController.removeAllChatMessages - id not provided!') + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + 'Error: chatMessagesController.removeAllChatMessages - id not provided!' + ) } const chatflowid = req.params.id const chatflow = await chatflowsService.getChatflowById(req.params.id) @@ -139,9 +144,6 @@ const removeAllChatMessages = async (req: Request, res: Response, next: NextFunc if (sessionId) deleteOptions.sessionId = sessionId if (chatType) deleteOptions.chatType = chatType const apiResponse = await chatMessagesService.removeAllChatMessages(chatId, chatflowid, deleteOptions) - if (apiResponse.executionError) { - res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) diff --git a/packages/server/src/controllers/chatflows/index.ts b/packages/server/src/controllers/chatflows/index.ts index 54f138e2..8923bf55 100644 --- a/packages/server/src/controllers/chatflows/index.ts +++ b/packages/server/src/controllers/chatflows/index.ts @@ -3,16 +3,18 @@ import chatflowsService from '../../services/chatflows' import { ChatFlow } from '../../database/entities/ChatFlow' import { createRateLimiter } from '../../utils/rateLimit' import { getApiKey } from '../../utils/apiKey' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { StatusCodes } from 'http-status-codes' const checkIfChatflowIsValidForStreaming = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: chatflowsRouter.checkIfChatflowIsValidForStreaming - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: chatflowsRouter.checkIfChatflowIsValidForStreaming - id not provided!` + ) } const apiResponse = await chatflowsService.checkIfChatflowIsValidForStreaming(req.params.id) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) @@ -21,13 +23,13 @@ const checkIfChatflowIsValidForStreaming = async (req: Request, res: Response, n const checkIfChatflowIsValidForUploads = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: chatflowsRouter.checkIfChatflowIsValidForUploads - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: chatflowsRouter.checkIfChatflowIsValidForUploads - id not provided!` + ) } const apiResponse = await chatflowsService.checkIfChatflowIsValidForUploads(req.params.id) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) @@ -36,8 +38,8 @@ const checkIfChatflowIsValidForUploads = async (req: Request, res: Response, nex const deleteChatflow = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: chatflowsRouter.deleteChatflow - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, `Error: chatflowsRouter.deleteChatflow - id not provided!`) } const apiResponse = await chatflowsService.deleteChatflow(req.params.id) return res.json(apiResponse) @@ -58,17 +60,17 @@ const getAllChatflows = async (req: Request, res: Response, next: NextFunction) // Get specific chatflow via api key const getChatflowByApiKey = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.apiKey === 'undefined' || req.params.apiKey === '') { - throw new Error(`Error: chatflowsRouter.getChatflowById - apiKey not provided!`) + if (typeof req.params === 'undefined' || !req.params.apiKey) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: chatflowsRouter.getChatflowByApiKey - apiKey not provided!` + ) } const apiKey = await getApiKey(req.params.apiKey) if (!apiKey) { return res.status(401).send('Unauthorized') } const apiResponse = await chatflowsService.getChatflowByApiKey(apiKey.id) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) @@ -77,13 +79,10 @@ const getChatflowByApiKey = async (req: Request, res: Response, next: NextFuncti const getChatflowById = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: chatflowsRouter.getChatflowById - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, `Error: chatflowsRouter.getChatflowById - id not provided!`) } const apiResponse = await chatflowsService.getChatflowById(req.params.id) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) @@ -92,8 +91,8 @@ const getChatflowById = async (req: Request, res: Response, next: NextFunction) const saveChatflow = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.body === 'undefined' || req.body === '') { - throw new Error(`Error: chatflowsRouter.saveChatflow - body not provided!`) + if (!req.body) { + throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, `Error: chatflowsRouter.saveChatflow - body not provided!`) } const body = req.body const newChatFlow = new ChatFlow() @@ -107,8 +106,8 @@ const saveChatflow = async (req: Request, res: Response, next: NextFunction) => const updateChatflow = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: chatflowsRouter.updateChatflow - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, `Error: chatflowsRouter.updateChatflow - id not provided!`) } const chatflow = await chatflowsService.getChatflowById(req.params.id) if (!chatflow) { @@ -131,13 +130,13 @@ const updateChatflow = async (req: Request, res: Response, next: NextFunction) = const getSinglePublicChatflow = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: chatflowsRouter.updateChatflow - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: chatflowsRouter.getSinglePublicChatflow - id not provided!` + ) } const apiResponse = await chatflowsService.getSinglePublicChatflow(req.params.id) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) @@ -146,13 +145,13 @@ const getSinglePublicChatflow = async (req: Request, res: Response, next: NextFu const getSinglePublicChatbotConfig = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: chatflowsRouter.getSinglePublicChatbotConfig - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: chatflowsRouter.getSinglePublicChatbotConfig - id not provided!` + ) } const apiResponse = await chatflowsService.getSinglePublicChatbotConfig(req.params.id) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) diff --git a/packages/server/src/controllers/components-credentials/index.ts b/packages/server/src/controllers/components-credentials/index.ts index 5f16aa46..de99a914 100644 --- a/packages/server/src/controllers/components-credentials/index.ts +++ b/packages/server/src/controllers/components-credentials/index.ts @@ -1,5 +1,7 @@ import { Request, Response, NextFunction } from 'express' import componentsCredentialsService from '../../services/components-credentials' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { StatusCodes } from 'http-status-codes' // Get all component credentials const getAllComponentsCredentials = async (req: Request, res: Response, next: NextFunction) => { @@ -14,8 +16,11 @@ const getAllComponentsCredentials = async (req: Request, res: Response, next: Ne // Get component credential via name const getComponentByName = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.name === 'undefined' || req.params.name === '') { - throw new Error(`Error: componentsCredentialsController.getComponentByName - name not provided!`) + if (typeof req.params === 'undefined' || !req.params.name) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: componentsCredentialsController.getComponentByName - name not provided!` + ) } const apiResponse = await componentsCredentialsService.getComponentByName(req.params.name) return res.json(apiResponse) @@ -27,8 +32,11 @@ const getComponentByName = async (req: Request, res: Response, next: NextFunctio // Returns specific component credential icon via name const getSingleComponentsCredentialIcon = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.name === 'undefined' || req.params.name === '') { - throw new Error(`Error: componentsCredentialsController.getSingleComponentsCredentialIcon - name not provided!`) + if (typeof req.params === 'undefined' || !req.params.name) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: componentsCredentialsController.getSingleComponentsCredentialIcon - name not provided!` + ) } const apiResponse = await componentsCredentialsService.getSingleComponentsCredentialIcon(req.params.name) return res.sendFile(apiResponse) diff --git a/packages/server/src/controllers/credentials/index.ts b/packages/server/src/controllers/credentials/index.ts index 2bc599a2..ad937443 100644 --- a/packages/server/src/controllers/credentials/index.ts +++ b/packages/server/src/controllers/credentials/index.ts @@ -1,10 +1,15 @@ import { Request, Response, NextFunction } from 'express' import credentialsService from '../../services/credentials' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { StatusCodes } from 'http-status-codes' const createCredential = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.body === 'undefined' || req.body === '') { - throw new Error(`Error: credentialsController.createCredential - body not provided!`) + if (!req.body) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: credentialsController.createCredential - body not provided!` + ) } const apiResponse = await credentialsService.createCredential(req.body) return res.json(apiResponse) @@ -15,13 +20,13 @@ const createCredential = async (req: Request, res: Response, next: NextFunction) const deleteCredentials = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: credentialsController.deleteCredentials - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: credentialsController.deleteCredentials - id not provided!` + ) } const apiResponse = await credentialsService.deleteCredentials(req.params.id) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) @@ -39,13 +44,13 @@ const getAllCredentials = async (req: Request, res: Response, next: NextFunction const getCredentialById = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: credentialsController.getCredentialById - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: credentialsController.getCredentialById - id not provided!` + ) } const apiResponse = await credentialsService.getCredentialById(req.params.id) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) @@ -54,16 +59,19 @@ const getCredentialById = async (req: Request, res: Response, next: NextFunction const updateCredential = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: credentialsController.updateCredential - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: credentialsController.updateCredential - id not provided!` + ) } - if (typeof req.body === 'undefined' || req.body === '') { - throw new Error(`Error: credentialsController.updateCredential - body not provided!`) + if (!req.body) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: credentialsController.updateCredential - body not provided!` + ) } const apiResponse = await credentialsService.updateCredential(req.params.id, req.body) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) diff --git a/packages/server/src/controllers/feedback/index.ts b/packages/server/src/controllers/feedback/index.ts index 08c95aff..936a3b87 100644 --- a/packages/server/src/controllers/feedback/index.ts +++ b/packages/server/src/controllers/feedback/index.ts @@ -1,10 +1,15 @@ import { Request, Response, NextFunction } from 'express' import feedbackService from '../../services/feedback' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { StatusCodes } from 'http-status-codes' const getAllChatMessageFeedback = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: feedbackController.getAllChatMessageFeedback - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: feedbackController.getAllChatMessageFeedback - id not provided!` + ) } const chatflowid = req.params.id const chatId = req.query?.chatId as string | undefined @@ -20,8 +25,11 @@ const getAllChatMessageFeedback = async (req: Request, res: Response, next: Next const createChatMessageFeedbackForChatflow = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.body === 'undefined' || req.body === '') { - throw new Error(`Error: feedbackController.createChatMessageFeedbackForChatflow - body not provided!`) + if (!req.body) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: feedbackController.createChatMessageFeedbackForChatflow - body not provided!` + ) } const apiResponse = await feedbackService.createChatMessageFeedbackForChatflow(req.body) return res.json(apiResponse) @@ -32,11 +40,17 @@ const createChatMessageFeedbackForChatflow = async (req: Request, res: Response, const updateChatMessageFeedbackForChatflow = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.body === 'undefined' || req.body === '') { - throw new Error(`Error: feedbackController.updateChatMessageFeedbackForChatflow - body not provided!`) + if (!req.body) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: feedbackController.updateChatMessageFeedbackForChatflow - body not provided!` + ) } - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: feedbackController.updateChatMessageFeedbackForChatflow - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: feedbackController.updateChatMessageFeedbackForChatflow - id not provided!` + ) } const apiResponse = await feedbackService.updateChatMessageFeedbackForChatflow(req.params.id, req.body) return res.json(apiResponse) diff --git a/packages/server/src/controllers/fetch-links/index.ts b/packages/server/src/controllers/fetch-links/index.ts index 586f1159..f3acce52 100644 --- a/packages/server/src/controllers/fetch-links/index.ts +++ b/packages/server/src/controllers/fetch-links/index.ts @@ -1,25 +1,27 @@ import { Request, Response, NextFunction } from 'express' import fetchLinksService from '../../services/fetch-links' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { StatusCodes } from 'http-status-codes' const getAllLinks = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.query.url === 'undefined' || req.query.url === '') { - throw new Error(`Error: fetchLinksController.getAllLinks - url not provided!`) + if (typeof req.query === 'undefined' || !req.query.url) { + throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, `Error: fetchLinksController.getAllLinks - url not provided!`) } - if (typeof req.query.relativeLinksMethod === 'undefined' || req.query.relativeLinksMethod === '') { - throw new Error(`Error: fetchLinksController.getAllLinks - relativeLinksMethod not provided!`) + if (typeof req.query === 'undefined' || !req.query.relativeLinksMethod) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: fetchLinksController.getAllLinks - relativeLinksMethod not provided!` + ) } - if (typeof req.query.limit === 'undefined' || req.query.limit === '') { - throw new Error(`Error: fetchLinksController.getAllLinks - limit not provided!`) + if (typeof req.query === 'undefined' || !req.query.limit) { + throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, `Error: fetchLinksController.getAllLinks - limit not provided!`) } const apiResponse = await fetchLinksService.getAllLinks( req.query.url as string, req.query.relativeLinksMethod as string, req.query.limit as string ) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) diff --git a/packages/server/src/controllers/flow-configs/index.ts b/packages/server/src/controllers/flow-configs/index.ts index ce576497..c0926266 100644 --- a/packages/server/src/controllers/flow-configs/index.ts +++ b/packages/server/src/controllers/flow-configs/index.ts @@ -1,15 +1,17 @@ import { Request, Response, NextFunction } from 'express' import flowConfigsService from '../../services/flow-configs' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { StatusCodes } from 'http-status-codes' const getSingleFlowConfig = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: flowConfigsController.getSingleFlowConfig - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: flowConfigsController.getSingleFlowConfig - id not provided!` + ) } const apiResponse = await flowConfigsService.getSingleFlowConfig(req.params.id) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) diff --git a/packages/server/src/controllers/ip/index.ts b/packages/server/src/controllers/ip/index.ts index 98f4ce72..6775f9f5 100644 --- a/packages/server/src/controllers/ip/index.ts +++ b/packages/server/src/controllers/ip/index.ts @@ -1,10 +1,15 @@ import { Request, Response, NextFunction } from 'express' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { StatusCodes } from 'http-status-codes' // Configure number of proxies in Host Environment const configureProxyNrInHostEnv = async (req: Request, res: Response, next: NextFunction) => { try { if (typeof req.ip === 'undefined' || req.ip) { - throw new Error(`Error: ipController.configureProxyNrInHostEnv - ip not provided!`) + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: ipController.configureProxyNrInHostEnv - ip not provided!` + ) } const apiResponse = { ip: req.ip, diff --git a/packages/server/src/controllers/load-prompts/index.ts b/packages/server/src/controllers/load-prompts/index.ts index 6fa38aef..6437e491 100644 --- a/packages/server/src/controllers/load-prompts/index.ts +++ b/packages/server/src/controllers/load-prompts/index.ts @@ -1,15 +1,17 @@ import { Request, Response, NextFunction } from 'express' import loadPromptsService from '../../services/load-prompts' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { StatusCodes } from 'http-status-codes' const createPrompt = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.body === 'undefined' || typeof req.body.promptName === 'undefined' || req.body.promptName === '') { - throw new Error(`Error: loadPromptsController.createPrompt - promptName not provided!`) + if (typeof req.body === 'undefined' || !req.body.promptName) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: loadPromptsController.createPrompt - promptName not provided!` + ) } const apiResponse = await loadPromptsService.createPrompt(req.body.promptName as string) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) diff --git a/packages/server/src/controllers/node-configs/index.ts b/packages/server/src/controllers/node-configs/index.ts index f8f90e1e..d6ef4a46 100644 --- a/packages/server/src/controllers/node-configs/index.ts +++ b/packages/server/src/controllers/node-configs/index.ts @@ -1,10 +1,15 @@ import { Request, Response, NextFunction } from 'express' import nodeConfigsService from '../../services/node-configs' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { StatusCodes } from 'http-status-codes' const getAllNodeConfigs = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.body === 'undefined' || req.body === '') { - throw new Error(`Error: nodeConfigsController.getAllNodeConfigs - body not provided!`) + if (!req.body) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: nodeConfigsController.getAllNodeConfigs - body not provided!` + ) } const apiResponse = await nodeConfigsService.getAllNodeConfigs(req.body) return res.json(apiResponse) diff --git a/packages/server/src/controllers/node-icons/index.ts b/packages/server/src/controllers/node-icons/index.ts index b423a96f..70cb58e4 100644 --- a/packages/server/src/controllers/node-icons/index.ts +++ b/packages/server/src/controllers/node-icons/index.ts @@ -1,5 +1,7 @@ import { Request, Response, NextFunction } from 'express' import { getRunningExpressApp } from '../../utils/getRunningExpressApp' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { StatusCodes } from 'http-status-codes' // Returns specific component node icon via name const getSingleNodeIcon = async (req: Request, res: Response, next: NextFunction) => { @@ -8,17 +10,26 @@ const getSingleNodeIcon = async (req: Request, res: Response, next: NextFunction if (Object.prototype.hasOwnProperty.call(appServer.nodesPool.componentNodes, req.params.name)) { const nodeInstance = appServer.nodesPool.componentNodes[req.params.name] if (nodeInstance.icon === undefined) { - throw new Error(`Error: nodeIconController.getSingleNodeIcon - Node ${req.params.name} icon not found`) + throw new InternalFlowiseError( + StatusCodes.NOT_FOUND, + `Error: nodeIconController.getSingleNodeIcon - Node ${req.params.name} icon not found` + ) } if (nodeInstance.icon.endsWith('.svg') || nodeInstance.icon.endsWith('.png') || nodeInstance.icon.endsWith('.jpg')) { const filepath = nodeInstance.icon res.sendFile(filepath) } else { - throw new Error(`Error: nodeIconController.getSingleNodeIcon - Node ${req.params.name} icon is missing icon`) + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: nodeIconController.getSingleNodeIcon - Node ${req.params.name} icon is missing icon` + ) } } else { - throw new Error(`Error: nodeIconController.getSingleNodeIcon - Node ${req.params.name} not found`) + throw new InternalFlowiseError( + StatusCodes.NOT_FOUND, + `Error: nodeIconController.getSingleNodeIcon - Node ${req.params.name} not found` + ) } } catch (error) { next(error) diff --git a/packages/server/src/controllers/nodes/index.ts b/packages/server/src/controllers/nodes/index.ts index ac448d93..eb20e400 100644 --- a/packages/server/src/controllers/nodes/index.ts +++ b/packages/server/src/controllers/nodes/index.ts @@ -1,5 +1,7 @@ import { Request, Response, NextFunction } from 'express' import nodesService from '../../services/nodes' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { StatusCodes } from 'http-status-codes' const getAllNodes = async (req: Request, res: Response, next: NextFunction) => { try { @@ -12,8 +14,8 @@ const getAllNodes = async (req: Request, res: Response, next: NextFunction) => { const getNodeByName = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.name === 'undefined' || req.params.name === '') { - throw new Error(`Error: nodesController.getNodeByName - name not provided!`) + if (typeof req.params === 'undefined' || !req.params.name) { + throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, `Error: nodesController.getNodeByName - name not provided!`) } const apiResponse = await nodesService.getNodeByName(req.params.name) return res.json(apiResponse) @@ -24,8 +26,8 @@ const getNodeByName = async (req: Request, res: Response, next: NextFunction) => const getSingleNodeIcon = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.name === 'undefined' || req.params.name === '') { - throw new Error(`Error: nodesController.getSingleNodeIcon - name not provided!`) + if (typeof req.params === 'undefined' || !req.params.name) { + throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, `Error: nodesController.getSingleNodeIcon - name not provided!`) } const apiResponse = await nodesService.getSingleNodeIcon(req.params.name) return res.sendFile(apiResponse) @@ -36,16 +38,19 @@ const getSingleNodeIcon = async (req: Request, res: Response, next: NextFunction const getSingleNodeAsyncOptions = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.body === 'undefined' || req.body === '') { - throw new Error(`Error: nodesController.getSingleNodeAsyncOptions - body not provided!`) + if (!req.body) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: nodesController.getSingleNodeAsyncOptions - body not provided!` + ) } - if (typeof req.params.name === 'undefined' || req.params.name === '') { - throw new Error(`Error: nodesController.getSingleNodeAsyncOptions - name not provided!`) + if (typeof req.params === 'undefined' || !req.params.name) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: nodesController.getSingleNodeAsyncOptions - name not provided!` + ) } const apiResponse = await nodesService.getSingleNodeAsyncOptions(req.params.name, req.body) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) @@ -54,13 +59,13 @@ const getSingleNodeAsyncOptions = async (req: Request, res: Response, next: Next const executeCustomFunction = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.body === 'undefined' || req.body === '') { - throw new Error(`Error: nodesController.executeCustomFunction - body not provided!`) + if (!req.body) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: nodesController.executeCustomFunction - body not provided!` + ) } const apiResponse = await nodesService.executeCustomFunction(req.body) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) diff --git a/packages/server/src/controllers/openai-assistants/index.ts b/packages/server/src/controllers/openai-assistants/index.ts index 539f2fbf..4e944038 100644 --- a/packages/server/src/controllers/openai-assistants/index.ts +++ b/packages/server/src/controllers/openai-assistants/index.ts @@ -4,17 +4,19 @@ import * as fs from 'fs' import openaiAssistantsService from '../../services/openai-assistants' import { getUserHome } from '../../utils' import contentDisposition from 'content-disposition' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { StatusCodes } from 'http-status-codes' // List available assistants const getAllOpenaiAssistants = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.query.credential === 'undefined' || req.query.credential === '') { - throw new Error(`Error: openaiAssistantsController.getAllOpenaiAssistants - credential not provided!`) + if (typeof req.query === 'undefined' || !req.query.credential) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: openaiAssistantsController.getAllOpenaiAssistants - credential not provided!` + ) } const apiResponse = await openaiAssistantsService.getAllOpenaiAssistants(req.query.credential as string) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) @@ -24,16 +26,19 @@ const getAllOpenaiAssistants = async (req: Request, res: Response, next: NextFun // Get assistant object const getSingleOpenaiAssistant = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: openaiAssistantsController.getSingleOpenaiAssistant - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: openaiAssistantsController.getSingleOpenaiAssistant - id not provided!` + ) } - if (typeof req.query.credential === 'undefined' || req.query.credential === '') { - throw new Error(`Error: openaiAssistantsController.getSingleOpenaiAssistant - credential not provided!`) + if (typeof req.query === 'undefined' || !req.query.credential) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: openaiAssistantsController.getSingleOpenaiAssistant - credential not provided!` + ) } const apiResponse = await openaiAssistantsService.getSingleOpenaiAssistant(req.query.credential as string, req.params.id) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) diff --git a/packages/server/src/controllers/predictions/index.ts b/packages/server/src/controllers/predictions/index.ts index 936bfe1c..aaebb92d 100644 --- a/packages/server/src/controllers/predictions/index.ts +++ b/packages/server/src/controllers/predictions/index.ts @@ -2,20 +2,28 @@ import { Request, Response, NextFunction } from 'express' import { getRateLimiter } from '../../utils/rateLimit' import chatflowsService from '../../services/chatflows' import logger from '../../utils/logger' -import { utilBuildChatflow } from '../../utils/buildChatflow' +import predictionsServices from '../../services/predictions' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { StatusCodes } from 'http-status-codes' // Send input message and get prediction result (External) const createPrediction = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: predictionsController.createPrediction - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: predictionsController.createPrediction - id not provided!` + ) } - if (typeof req.body === 'undefined' || req.body === '') { - throw new Error(`Error: predictionsController.createPrediction - body not provided!`) + if (!req.body) { + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: predictionsController.createPrediction - body not provided!` + ) } const chatflow = await chatflowsService.getChatflowById(req.params.id) if (!chatflow) { - return res.status(404).send(`Chatflow ${req.params.id} not found`) + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Chatflow ${req.params.id} not found`) } let isDomainAllowed = true logger.info(`[server]: Request originated from ${req.headers.origin}`) @@ -37,15 +45,12 @@ const createPrediction = async (req: Request, res: Response, next: NextFunction) }).length > 0 } } - if (isDomainAllowed) { - const apiResponse = await utilBuildChatflow(req, req.io) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } + //@ts-ignore + const apiResponse = await predictionsServices.buildChatflow(req, req?.io) return res.json(apiResponse) } else { - return res.status(401).send(`This site is not allowed to access this chatbot`) + throw new InternalFlowiseError(StatusCodes.UNAUTHORIZED, `This site is not allowed to access this chatbot`) } } catch (error) { next(error) diff --git a/packages/server/src/controllers/stats/index.ts b/packages/server/src/controllers/stats/index.ts index e1c97c49..e4dd4dad 100644 --- a/packages/server/src/controllers/stats/index.ts +++ b/packages/server/src/controllers/stats/index.ts @@ -1,11 +1,14 @@ +import { StatusCodes } from 'http-status-codes' import { Request, Response, NextFunction } from 'express' import statsService from '../../services/stats' import { chatType } from '../../Interface' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { getErrorMessage } from '../../errors/utils' const getChatflowStats = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: statsController.getChatflowStats - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, `Error: statsController.getChatflowStats - id not provided!`) } const chatflowid = req.params.id let chatTypeFilter = req.query?.chatType as chatType | undefined @@ -22,13 +25,13 @@ const getChatflowStats = async (req: Request, res: Response, next: NextFunction) chatTypeFilter = chatType.INTERNAL } } catch (e) { - return res.status(500).send(e) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: statsController.getChatflowStats - ${getErrorMessage(e)}` + ) } } const apiResponse = await statsService.getChatflowStats(chatflowid, chatTypeFilter, startDate, endDate, '', true) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) diff --git a/packages/server/src/controllers/tools/index.ts b/packages/server/src/controllers/tools/index.ts index 196032f6..35398d13 100644 --- a/packages/server/src/controllers/tools/index.ts +++ b/packages/server/src/controllers/tools/index.ts @@ -1,15 +1,14 @@ import { Request, Response, NextFunction } from 'express' import toolsService from '../../services/tools' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { StatusCodes } from 'http-status-codes' -const creatTool = async (req: Request, res: Response, next: NextFunction) => { +const createTool = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.body === 'undefined' || req.body === '') { - throw new Error(`Error: toolsController.creatTool - body not provided!`) - } - const apiResponse = await toolsService.creatTool(req.body) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) + if (!req.body) { + throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, `Error: toolsController.createTool - body not provided!`) } + const apiResponse = await toolsService.createTool(req.body) return res.json(apiResponse) } catch (error) { next(error) @@ -18,13 +17,10 @@ const creatTool = async (req: Request, res: Response, next: NextFunction) => { const deleteTool = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: toolsController.deleteTool - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, `Error: toolsController.deleteTool - id not provided!`) } const apiResponse = await toolsService.deleteTool(req.params.id) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) @@ -34,9 +30,6 @@ const deleteTool = async (req: Request, res: Response, next: NextFunction) => { const getAllTools = async (req: Request, res: Response, next: NextFunction) => { try { const apiResponse = await toolsService.getAllTools() - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) @@ -45,13 +38,10 @@ const getAllTools = async (req: Request, res: Response, next: NextFunction) => { const getToolById = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: toolsController.getToolById - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, `Error: toolsController.getToolById - id not provided!`) } const apiResponse = await toolsService.getToolById(req.params.id) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) @@ -60,16 +50,13 @@ const getToolById = async (req: Request, res: Response, next: NextFunction) => { const updateTool = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error(`Error: toolsController.updateTool - id not provided!`) + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, `Error: toolsController.updateTool - id not provided!`) } - if (typeof req.body === 'undefined' || req.body === '') { - throw new Error(`Error: toolsController.deleteTool - body not provided!`) + if (!req.body) { + throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, `Error: toolsController.deleteTool - body not provided!`) } const apiResponse = await toolsService.updateTool(req.params.id, req.body) - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) @@ -77,7 +64,7 @@ const updateTool = async (req: Request, res: Response, next: NextFunction) => { } export default { - creatTool, + createTool, deleteTool, getAllTools, getToolById, diff --git a/packages/server/src/controllers/variables/index.ts b/packages/server/src/controllers/variables/index.ts index 4dfd7492..a124255a 100644 --- a/packages/server/src/controllers/variables/index.ts +++ b/packages/server/src/controllers/variables/index.ts @@ -1,11 +1,16 @@ import { Request, Response, NextFunction } from 'express' import variablesService from '../../services/variables' import { Variable } from '../../database/entities/Variable' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { StatusCodes } from 'http-status-codes' const createVariable = async (req: Request, res: Response, next: NextFunction) => { try { if (typeof req.body === 'undefined') { - throw new Error(`Error: variablesController.createVariable - body not provided!`) + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + `Error: variablesController.createVariable - body not provided!` + ) } const body = req.body const newVariable = new Variable() @@ -19,8 +24,8 @@ const createVariable = async (req: Request, res: Response, next: NextFunction) = const deleteVariable = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error('Error: variablesController.deleteVariable - id not provided!') + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, 'Error: variablesController.deleteVariable - id not provided!') } const apiResponse = await variablesService.deleteVariable(req.params.id) return res.json(apiResponse) @@ -40,11 +45,14 @@ const getAllVariables = async (req: Request, res: Response, next: NextFunction) const updateVariable = async (req: Request, res: Response, next: NextFunction) => { try { - if (typeof req.params.id === 'undefined' || req.params.id === '') { - throw new Error('Error: variablesController.updateVariable - id not provided!') + if (typeof req.params === 'undefined' || !req.params.id) { + throw new InternalFlowiseError(StatusCodes.PRECONDITION_FAILED, 'Error: variablesController.updateVariable - id not provided!') } if (typeof req.body === 'undefined') { - throw new Error('Error: variablesController.updateVariable - body not provided!') + throw new InternalFlowiseError( + StatusCodes.PRECONDITION_FAILED, + 'Error: variablesController.updateVariable - body not provided!' + ) } const variable = await variablesService.getVariableById(req.params.id) if (!variable) { diff --git a/packages/server/src/controllers/vectors/index.ts b/packages/server/src/controllers/vectors/index.ts index 21f8e3da..5d10bb68 100644 --- a/packages/server/src/controllers/vectors/index.ts +++ b/packages/server/src/controllers/vectors/index.ts @@ -12,7 +12,8 @@ const getRateLimiterMiddleware = async (req: Request, res: Response, next: NextF const upsertVectorMiddleware = async (req: Request, res: Response, next: NextFunction) => { try { - return await vectorsService.upsertVectorMiddleware(req, res) + const apiResponse = await vectorsService.upsertVectorMiddleware(req) + return res.json(apiResponse) } catch (error) { next(error) } @@ -20,7 +21,9 @@ const upsertVectorMiddleware = async (req: Request, res: Response, next: NextFun const createInternalUpsert = async (req: Request, res: Response, next: NextFunction) => { try { - return await vectorsService.upsertVectorMiddleware(req, res, true) + const isInternal = true + const apiResponse = await vectorsService.upsertVectorMiddleware(req, isInternal) + return res.json(apiResponse) } catch (error) { next(error) } diff --git a/packages/server/src/controllers/versions/index.ts b/packages/server/src/controllers/versions/index.ts index 7a6f76c4..26697620 100644 --- a/packages/server/src/controllers/versions/index.ts +++ b/packages/server/src/controllers/versions/index.ts @@ -4,9 +4,6 @@ import versionsService from '../../services/versions' const getVersion = async (req: Request, res: Response, next: NextFunction) => { try { const apiResponse = await versionsService.getVersion() - if (apiResponse.executionError) { - return res.status(apiResponse.status).send(apiResponse.msg) - } return res.json(apiResponse) } catch (error) { next(error) diff --git a/packages/server/src/errors/apiError/index.ts b/packages/server/src/errors/internalFlowiseError/index.ts similarity index 84% rename from packages/server/src/errors/apiError/index.ts rename to packages/server/src/errors/internalFlowiseError/index.ts index 641e2d5a..4e836514 100644 --- a/packages/server/src/errors/apiError/index.ts +++ b/packages/server/src/errors/internalFlowiseError/index.ts @@ -1,4 +1,4 @@ -export class ApiError extends Error { +export class InternalFlowiseError extends Error { statusCode: number constructor(statusCode: number, message: string) { super(message) diff --git a/packages/server/src/errors/utils.ts b/packages/server/src/errors/utils.ts new file mode 100644 index 00000000..12ba0a67 --- /dev/null +++ b/packages/server/src/errors/utils.ts @@ -0,0 +1,25 @@ +type ErrorWithMessage = { + message: string +} + +const isErrorWithMessage = (error: unknown): error is ErrorWithMessage => { + return ( + typeof error === 'object' && error !== null && 'message' in error && typeof (error as Record).message === 'string' + ) +} + +const toErrorWithMessage = (maybeError: unknown): ErrorWithMessage => { + if (isErrorWithMessage(maybeError)) return maybeError + + try { + return new Error(JSON.stringify(maybeError)) + } catch { + // fallback in case there's an error stringifying the maybeError + // like with circular references for example. + return new Error(String(maybeError)) + } +} + +export const getErrorMessage = (error: unknown) => { + return toErrorWithMessage(error).message +} diff --git a/packages/server/src/middlewares/errors/index.ts b/packages/server/src/middlewares/errors/index.ts index 3e97daf6..ea0ab513 100644 --- a/packages/server/src/middlewares/errors/index.ts +++ b/packages/server/src/middlewares/errors/index.ts @@ -1,10 +1,10 @@ import { NextFunction, Request, Response } from 'express' import { StatusCodes } from 'http-status-codes' -import { ApiError } from '../../errors/apiError' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' // we need eslint because we have to pass next arg for the error middleware // eslint-disable-next-line -async function errorHandlerMiddleware(err: ApiError, req: Request, res: Response, next: NextFunction) { +async function errorHandlerMiddleware(err: InternalFlowiseError, req: Request, res: Response, next: NextFunction) { let displayedError = { statusCode: err.statusCode || StatusCodes.INTERNAL_SERVER_ERROR, success: false, diff --git a/packages/server/src/routes/apikey/index.ts b/packages/server/src/routes/apikey/index.ts index e82924d8..566d12e8 100644 --- a/packages/server/src/routes/apikey/index.ts +++ b/packages/server/src/routes/apikey/index.ts @@ -9,9 +9,9 @@ router.post('/', apikeyController.createApiKey) router.get('/', apikeyController.getAllApiKeys) // UPDATE -router.put('/:id', apikeyController.updateApiKey) +router.put(['/', '/:id'], apikeyController.updateApiKey) // DELETE -router.delete('/:id', apikeyController.deleteApiKey) +router.delete(['/', '/:id'], apikeyController.deleteApiKey) export default router diff --git a/packages/server/src/routes/assistants/index.ts b/packages/server/src/routes/assistants/index.ts index 494f8f9d..7b01cdd0 100644 --- a/packages/server/src/routes/assistants/index.ts +++ b/packages/server/src/routes/assistants/index.ts @@ -4,16 +4,16 @@ import assistantsController from '../../controllers/assistants' const router = express.Router() // CREATE -router.post('/', assistantsController.creatAssistant) +router.post('/', assistantsController.createAssistant) // READ router.get('/', assistantsController.getAllAssistants) -router.get('/:id', assistantsController.getAssistantById) +router.get(['/', '/:id'], assistantsController.getAssistantById) // UPDATE -router.put('/:id', assistantsController.updateAssistant) +router.put(['/', '/:id'], assistantsController.updateAssistant) // DELETE -router.delete('/:id', assistantsController.deleteAssistant) +router.delete(['/', '/:id'], assistantsController.deleteAssistant) export default router diff --git a/packages/server/src/routes/chat-messages/index.ts b/packages/server/src/routes/chat-messages/index.ts index dbb3e9f1..64dacb13 100644 --- a/packages/server/src/routes/chat-messages/index.ts +++ b/packages/server/src/routes/chat-messages/index.ts @@ -3,14 +3,14 @@ import chatMessageController from '../../controllers/chat-messages' const router = express.Router() // CREATE -router.post('/:id', chatMessageController.createChatMessage) +router.post(['/', '/:id'], chatMessageController.createChatMessage) // READ -router.get('/:id', chatMessageController.getAllChatMessages) +router.get(['/', '/:id'], chatMessageController.getAllChatMessages) // UPDATE // DELETE -router.delete('/:id', chatMessageController.removeAllChatMessages) +router.delete(['/', '/:id'], chatMessageController.removeAllChatMessages) export default router diff --git a/packages/server/src/routes/chatflows-streaming/index.ts b/packages/server/src/routes/chatflows-streaming/index.ts index 34ca4e0c..cc8dc257 100644 --- a/packages/server/src/routes/chatflows-streaming/index.ts +++ b/packages/server/src/routes/chatflows-streaming/index.ts @@ -4,6 +4,6 @@ import chatflowsController from '../../controllers/chatflows' const router = express.Router() // READ -router.get('/:id', chatflowsController.checkIfChatflowIsValidForStreaming) +router.get(['/', '/:id'], chatflowsController.checkIfChatflowIsValidForStreaming) export default router diff --git a/packages/server/src/routes/chatflows-uploads/index.ts b/packages/server/src/routes/chatflows-uploads/index.ts index b3b3ff03..591718c2 100644 --- a/packages/server/src/routes/chatflows-uploads/index.ts +++ b/packages/server/src/routes/chatflows-uploads/index.ts @@ -4,6 +4,6 @@ import chatflowsController from '../../controllers/chatflows' const router = express.Router() // READ -router.get('/:id', chatflowsController.checkIfChatflowIsValidForUploads) +router.get(['/', '/:id'], chatflowsController.checkIfChatflowIsValidForUploads) export default router diff --git a/packages/server/src/routes/chatflows/index.ts b/packages/server/src/routes/chatflows/index.ts index 8cd3fcc0..8fb457fd 100644 --- a/packages/server/src/routes/chatflows/index.ts +++ b/packages/server/src/routes/chatflows/index.ts @@ -7,13 +7,13 @@ router.post('/', chatflowsController.saveChatflow) // READ router.get('/', chatflowsController.getAllChatflows) -router.get('/:id', chatflowsController.getChatflowById) -router.get('/apikey/:apikey', chatflowsController.getChatflowByApiKey) +router.get(['/', '/:id'], chatflowsController.getChatflowById) +router.get(['/apikey/', '/apikey/:apikey'], chatflowsController.getChatflowByApiKey) // UPDATE -router.put('/:id', chatflowsController.updateChatflow) +router.put(['/', '/:id'], chatflowsController.updateChatflow) // DELETE -router.delete('/:id', chatflowsController.deleteChatflow) +router.delete(['/', '/:id'], chatflowsController.deleteChatflow) export default router diff --git a/packages/server/src/routes/components-credentials-icon/index.ts b/packages/server/src/routes/components-credentials-icon/index.ts index 364a87ba..50d22134 100644 --- a/packages/server/src/routes/components-credentials-icon/index.ts +++ b/packages/server/src/routes/components-credentials-icon/index.ts @@ -5,7 +5,7 @@ const router = express.Router() // CREATE // READ -router.get('/:name', componentsCredentialsController.getSingleComponentsCredentialIcon) +router.get(['/', '/:name'], componentsCredentialsController.getSingleComponentsCredentialIcon) // UPDATE diff --git a/packages/server/src/routes/components-credentials/index.ts b/packages/server/src/routes/components-credentials/index.ts index 2f7b2364..16aff2ff 100644 --- a/packages/server/src/routes/components-credentials/index.ts +++ b/packages/server/src/routes/components-credentials/index.ts @@ -4,6 +4,6 @@ const router = express.Router() // READ router.get('/', componentsCredentialsController.getAllComponentsCredentials) -router.get('/:name', componentsCredentialsController.getComponentByName) +router.get(['/', '/:name'], componentsCredentialsController.getComponentByName) export default router diff --git a/packages/server/src/routes/credentials/index.ts b/packages/server/src/routes/credentials/index.ts index 0229798b..9f118b49 100644 --- a/packages/server/src/routes/credentials/index.ts +++ b/packages/server/src/routes/credentials/index.ts @@ -7,12 +7,12 @@ router.post('/', credentialsController.createCredential) // READ router.get('/', credentialsController.getAllCredentials) -router.get('/:id', credentialsController.getCredentialById) +router.get(['/', '/:id'], credentialsController.getCredentialById) // UPDATE -router.put('/:id', credentialsController.updateCredential) +router.put(['/', '/:id'], credentialsController.updateCredential) // DELETE -router.delete('/:id', credentialsController.deleteCredentials) +router.delete(['/', '/:id'], credentialsController.deleteCredentials) export default router diff --git a/packages/server/src/routes/feedback/index.ts b/packages/server/src/routes/feedback/index.ts index 3502a9fb..bcec7c74 100644 --- a/packages/server/src/routes/feedback/index.ts +++ b/packages/server/src/routes/feedback/index.ts @@ -3,12 +3,12 @@ import feedbackController from '../../controllers/feedback' const router = express.Router() // CREATE -router.post('/:id', feedbackController.createChatMessageFeedbackForChatflow) +router.post(['/', '/:id'], feedbackController.createChatMessageFeedbackForChatflow) // READ -router.get('/:id', feedbackController.getAllChatMessageFeedback) +router.get(['/', '/:id'], feedbackController.getAllChatMessageFeedback) // UPDATE -router.put('/:id', feedbackController.updateChatMessageFeedbackForChatflow) +router.put(['/', '/:id'], feedbackController.updateChatMessageFeedbackForChatflow) export default router diff --git a/packages/server/src/routes/flow-config/index.ts b/packages/server/src/routes/flow-config/index.ts index 1aa46517..bd841507 100644 --- a/packages/server/src/routes/flow-config/index.ts +++ b/packages/server/src/routes/flow-config/index.ts @@ -5,7 +5,7 @@ const router = express.Router() // CREATE // READ -router.get('/:id', flowConfigsController.getSingleFlowConfig) +router.get(['/', '/:id'], flowConfigsController.getSingleFlowConfig) // UPDATE diff --git a/packages/server/src/routes/internal-chat-messages/index.ts b/packages/server/src/routes/internal-chat-messages/index.ts index fe05fdbc..5dcf1e67 100644 --- a/packages/server/src/routes/internal-chat-messages/index.ts +++ b/packages/server/src/routes/internal-chat-messages/index.ts @@ -5,7 +5,7 @@ const router = express.Router() // CREATE // READ -router.get('/:id', chatMessagesController.getAllInternalChatMessages) +router.get(['/', '/:id'], chatMessagesController.getAllInternalChatMessages) // UPDATE diff --git a/packages/server/src/routes/internal-predictions/index.ts b/packages/server/src/routes/internal-predictions/index.ts index 6e1c17ba..8e39dce2 100644 --- a/packages/server/src/routes/internal-predictions/index.ts +++ b/packages/server/src/routes/internal-predictions/index.ts @@ -3,6 +3,6 @@ import internalPredictionsController from '../../controllers/internal-prediction const router = express.Router() // CREATE -router.post('/:id', internalPredictionsController.createInternalPrediction) +router.post(['/', '/:id'], internalPredictionsController.createInternalPrediction) export default router diff --git a/packages/server/src/routes/node-icons/index.ts b/packages/server/src/routes/node-icons/index.ts index 0781226a..3dc51b96 100644 --- a/packages/server/src/routes/node-icons/index.ts +++ b/packages/server/src/routes/node-icons/index.ts @@ -5,7 +5,7 @@ const router = express.Router() // CREATE // READ -router.get('/:name', nodesController.getSingleNodeIcon) +router.get(['/', '/:name'], nodesController.getSingleNodeIcon) // UPDATE diff --git a/packages/server/src/routes/node-load-methods/index.ts b/packages/server/src/routes/node-load-methods/index.ts index 941190f1..317fd81c 100644 --- a/packages/server/src/routes/node-load-methods/index.ts +++ b/packages/server/src/routes/node-load-methods/index.ts @@ -2,6 +2,6 @@ import express from 'express' import nodesRouter from '../../controllers/nodes' const router = express.Router() -router.post('/:name', nodesRouter.getSingleNodeAsyncOptions) +router.post(['/', '/:name'], nodesRouter.getSingleNodeAsyncOptions) export default router diff --git a/packages/server/src/routes/nodes/index.ts b/packages/server/src/routes/nodes/index.ts index b875036e..fd036930 100644 --- a/packages/server/src/routes/nodes/index.ts +++ b/packages/server/src/routes/nodes/index.ts @@ -4,6 +4,6 @@ const router = express.Router() // READ router.get('/', nodesController.getAllNodes) -router.get('/:name', nodesController.getNodeByName) +router.get(['/', '/:name'], nodesController.getNodeByName) export default router diff --git a/packages/server/src/routes/openai-assistants/index.ts b/packages/server/src/routes/openai-assistants/index.ts index 6e3378fd..1c82a921 100644 --- a/packages/server/src/routes/openai-assistants/index.ts +++ b/packages/server/src/routes/openai-assistants/index.ts @@ -6,7 +6,7 @@ const router = express.Router() // READ router.get('/', openaiAssistantsController.getAllOpenaiAssistants) -router.get('/:id', openaiAssistantsController.getSingleOpenaiAssistant) +router.get(['/', '/:id'], openaiAssistantsController.getSingleOpenaiAssistant) // UPDATE diff --git a/packages/server/src/routes/predictions/index.ts b/packages/server/src/routes/predictions/index.ts index 613c6760..ded2d342 100644 --- a/packages/server/src/routes/predictions/index.ts +++ b/packages/server/src/routes/predictions/index.ts @@ -8,6 +8,6 @@ const router = express.Router() const upload = multer({ dest: `${path.join(__dirname, '..', '..', '..', 'uploads')}/` }) // CREATE -router.post('/:id', upload.array('files'), predictionsController.getRateLimiterMiddleware, predictionsController.createPrediction) +router.post(['/', '/:id'], upload.array('files'), predictionsController.getRateLimiterMiddleware, predictionsController.createPrediction) export default router diff --git a/packages/server/src/routes/public-chatbots/index.ts b/packages/server/src/routes/public-chatbots/index.ts index 5a367c68..18ee9e4c 100644 --- a/packages/server/src/routes/public-chatbots/index.ts +++ b/packages/server/src/routes/public-chatbots/index.ts @@ -5,7 +5,7 @@ const router = express.Router() // CREATE // READ -router.get('/:id', chatflowsController.getSinglePublicChatbotConfig) +router.get(['/', '/:id'], chatflowsController.getSinglePublicChatbotConfig) // UPDATE diff --git a/packages/server/src/routes/public-chatflows/index.ts b/packages/server/src/routes/public-chatflows/index.ts index 97e23ea7..640fe3a6 100644 --- a/packages/server/src/routes/public-chatflows/index.ts +++ b/packages/server/src/routes/public-chatflows/index.ts @@ -5,7 +5,7 @@ const router = express.Router() // CREATE // READ -router.get('/:id', chatflowsController.getSinglePublicChatflow) +router.get(['/', '/:id'], chatflowsController.getSinglePublicChatflow) // UPDATE diff --git a/packages/server/src/routes/stats/index.ts b/packages/server/src/routes/stats/index.ts index ea6d8db3..8ca64d3d 100644 --- a/packages/server/src/routes/stats/index.ts +++ b/packages/server/src/routes/stats/index.ts @@ -4,6 +4,6 @@ import statsController from '../../controllers/stats' const router = express.Router() // READ -router.get('/:id', statsController.getChatflowStats) +router.get(['/', '/:id'], statsController.getChatflowStats) export default router diff --git a/packages/server/src/routes/tools/index.ts b/packages/server/src/routes/tools/index.ts index 4d63b161..e97fb5cf 100644 --- a/packages/server/src/routes/tools/index.ts +++ b/packages/server/src/routes/tools/index.ts @@ -4,16 +4,16 @@ import toolsController from '../../controllers/tools' const router = express.Router() // CREATE -router.post('/', toolsController.creatTool) +router.post('/', toolsController.createTool) // READ router.get('/', toolsController.getAllTools) -router.get('/:id', toolsController.getToolById) +router.get(['/', '/:id'], toolsController.getToolById) // UPDATE -router.put('/:id', toolsController.updateTool) +router.put(['/', '/:id'], toolsController.updateTool) // DELETE -router.delete('/:id', toolsController.deleteTool) +router.delete(['/', '/:id'], toolsController.deleteTool) export default router diff --git a/packages/server/src/routes/upsert-history/index.ts b/packages/server/src/routes/upsert-history/index.ts index 1f4d9d02..3e3c9c1a 100644 --- a/packages/server/src/routes/upsert-history/index.ts +++ b/packages/server/src/routes/upsert-history/index.ts @@ -5,7 +5,7 @@ const router = express.Router() // CREATE // READ -router.get('/:id', upsertHistoryController.getAllUpsertHistory) +router.get(['/', '/:id'], upsertHistoryController.getAllUpsertHistory) // PATCH router.patch('/', upsertHistoryController.patchDeleteUpsertHistory) diff --git a/packages/server/src/routes/variables/index.ts b/packages/server/src/routes/variables/index.ts index eece5558..f6d3625a 100644 --- a/packages/server/src/routes/variables/index.ts +++ b/packages/server/src/routes/variables/index.ts @@ -10,9 +10,9 @@ router.post('/', variablesController.createVariable) router.get('/', variablesController.getAllVariables) // UPDATE -router.put('/:id', variablesController.updateVariable) +router.put(['/', '/:id'], variablesController.updateVariable) // DELETE -router.delete('/:id', variablesController.deleteVariable) +router.delete(['/', '/:id'], variablesController.deleteVariable) export default router diff --git a/packages/server/src/routes/vectors/index.ts b/packages/server/src/routes/vectors/index.ts index 21ffd97d..b0da82b6 100644 --- a/packages/server/src/routes/vectors/index.ts +++ b/packages/server/src/routes/vectors/index.ts @@ -8,7 +8,12 @@ const router = express.Router() const upload = multer({ dest: `${path.join(__dirname, '..', '..', '..', 'uploads')}/` }) // CREATE -router.post('/upsert/:id', upload.array('files'), vectorsController.getRateLimiterMiddleware, vectorsController.upsertVectorMiddleware) -router.post('/internal-upsert/:id', vectorsController.createInternalUpsert) +router.post( + ['/upsert/', '/upsert/:id'], + upload.array('files'), + vectorsController.getRateLimiterMiddleware, + vectorsController.upsertVectorMiddleware +) +router.post(['/internal-upsert/', '/internal-upsert/:id'], vectorsController.createInternalUpsert) export default router diff --git a/packages/server/src/routes/verify/index.ts b/packages/server/src/routes/verify/index.ts index 414e6d0f..b00a59aa 100644 --- a/packages/server/src/routes/verify/index.ts +++ b/packages/server/src/routes/verify/index.ts @@ -3,6 +3,6 @@ import apikeyController from '../../controllers/apikey' const router = express.Router() // READ -router.get('/apikey/:apikey', apikeyController.verifyApiKey) +router.get(['/apikey/', '/apikey/:apikey'], apikeyController.verifyApiKey) export default router diff --git a/packages/server/src/services/apikey/index.ts b/packages/server/src/services/apikey/index.ts index 5a1bc334..0bb09d02 100644 --- a/packages/server/src/services/apikey/index.ts +++ b/packages/server/src/services/apikey/index.ts @@ -1,6 +1,9 @@ +import { StatusCodes } from 'http-status-codes' import { addAPIKey, deleteAPIKey, getAPIKeys, updateAPIKey } from '../../utils/apiKey' import { addChatflowsCount } from '../../utils/addChatflowsCount' import { getApiKey } from '../../utils/apiKey' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { getErrorMessage } from '../../errors/utils' const getAllApiKeys = async () => { try { @@ -8,7 +11,7 @@ const getAllApiKeys = async () => { const dbResponse = await addChatflowsCount(keys) return dbResponse } catch (error) { - throw new Error(`Error: apikeyService.getAllApiKeys - ${error}`) + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Error: apikeyService.getAllApiKeys - ${getErrorMessage(error)}`) } } @@ -18,7 +21,7 @@ const createApiKey = async (keyName: string) => { const dbResponse = await addChatflowsCount(keys) return dbResponse } catch (error) { - throw new Error(`Error: apikeyService.createApiKey - ${error}`) + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Error: apikeyService.createApiKey - ${getErrorMessage(error)}`) } } @@ -29,7 +32,7 @@ const updateApiKey = async (id: string, keyName: string) => { const dbResponse = await addChatflowsCount(keys) return dbResponse } catch (error) { - throw new Error(`Error: apikeyService.updateApiKey - ${error}`) + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Error: apikeyService.updateApiKey - ${getErrorMessage(error)}`) } } @@ -39,7 +42,7 @@ const deleteApiKey = async (id: string) => { const dbResponse = await addChatflowsCount(keys) return dbResponse } catch (error) { - throw new Error(`Error: apikeyService.deleteApiKey - ${error}`) + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Error: apikeyService.deleteApiKey - ${getErrorMessage(error)}`) } } @@ -47,16 +50,12 @@ const verifyApiKey = async (paramApiKey: string): Promise => { try { const apiKey = await getApiKey(paramApiKey) if (!apiKey) { - return { - executionError: true, - status: 401, - msg: `Unauthorized` - } + throw new InternalFlowiseError(StatusCodes.UNAUTHORIZED, `Unauthorized`) } const dbResponse = 'OK' return dbResponse } catch (error) { - throw new Error(`Error: apikeyService.verifyApiKey - ${error}`) + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Error: apikeyService.verifyApiKey - ${getErrorMessage(error)}`) } } diff --git a/packages/server/src/services/assistants/index.ts b/packages/server/src/services/assistants/index.ts index 8b5a431f..f451c473 100644 --- a/packages/server/src/services/assistants/index.ts +++ b/packages/server/src/services/assistants/index.ts @@ -1,21 +1,20 @@ import OpenAI from 'openai' import path from 'path' import * as fs from 'fs' +import { StatusCodes } from 'http-status-codes' import { uniqWith, isEqual } from 'lodash' import { getRunningExpressApp } from '../../utils/getRunningExpressApp' import { Assistant } from '../../database/entities/Assistant' import { Credential } from '../../database/entities/Credential' import { getUserHome, decryptCredentialData, getAppVersion } from '../../utils' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { getErrorMessage } from '../../errors/utils' -const creatAssistant = async (requestBody: any): Promise => { +const createAssistant = async (requestBody: any): Promise => { try { const appServer = getRunningExpressApp() if (!requestBody.details) { - return { - executionError: true, - status: 500, - msg: `Invalid request body` - } + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Invalid request body`) } const assistantDetails = JSON.parse(requestBody.details) try { @@ -24,22 +23,14 @@ const creatAssistant = async (requestBody: any): Promise => { }) if (!credential) { - return { - executionError: true, - status: 404, - msg: `Credential ${requestBody.credential} not found` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Credential ${requestBody.credential} not found`) } // Decrpyt credentialData const decryptedCredentialData = await decryptCredentialData(credential.encryptedData) const openAIApiKey = decryptedCredentialData['openAIApiKey'] if (!openAIApiKey) { - return { - executionError: true, - status: 404, - msg: `OpenAI ApiKey not found` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `OpenAI ApiKey not found`) } const openai = new OpenAI({ apiKey: openAIApiKey }) @@ -121,11 +112,7 @@ const creatAssistant = async (requestBody: any): Promise => { requestBody.details = JSON.stringify(newAssistantDetails) } catch (error) { - return { - executionError: true, - status: 500, - msg: `Error creating new assistant: ${error}` - } + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Error creating new assistant - ${getErrorMessage(error)}`) } const newAssistant = new Assistant() Object.assign(newAssistant, requestBody) @@ -139,7 +126,10 @@ const creatAssistant = async (requestBody: any): Promise => { }) return dbResponse } catch (error) { - throw new Error(`Error: assistantsService.creatTool - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: assistantsService.createAssistant - ${getErrorMessage(error)}` + ) } } @@ -150,11 +140,7 @@ const deleteAssistant = async (assistantId: string, isDeleteBoth: any): Promise< id: assistantId }) if (!assistant) { - return { - executionError: true, - status: 404, - msg: `Assistant ${assistantId} not found` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Assistant ${assistantId} not found`) } try { const assistantDetails = JSON.parse(assistant.details) @@ -163,22 +149,14 @@ const deleteAssistant = async (assistantId: string, isDeleteBoth: any): Promise< }) if (!credential) { - return { - executionError: true, - status: 404, - msg: `Credential ${assistant.credential} not found` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Credential ${assistant.credential} not found`) } // Decrpyt credentialData const decryptedCredentialData = await decryptCredentialData(credential.encryptedData) const openAIApiKey = decryptedCredentialData['openAIApiKey'] if (!openAIApiKey) { - return { - executionError: true, - status: 404, - msg: `OpenAI ApiKey not found` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `OpenAI ApiKey not found`) } const openai = new OpenAI({ apiKey: openAIApiKey }) @@ -189,15 +167,14 @@ const deleteAssistant = async (assistantId: string, isDeleteBoth: any): Promise< if (error.status === 404 && error.type === 'invalid_request_error') { return 'OK' } else { - return { - executionError: true, - status: 500, - msg: `Error deleting assistant: ${error}` - } + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Error deleting assistant - ${getErrorMessage(error)}`) } } } catch (error) { - throw new Error(`Error: assistantsService.deleteTool - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: assistantsService.deleteAssistant - ${getErrorMessage(error)}` + ) } } @@ -207,7 +184,10 @@ const getAllAssistants = async (): Promise => { const dbResponse = await appServer.AppDataSource.getRepository(Assistant).find() return dbResponse } catch (error) { - throw new Error(`Error: assistantsService.getAllAssistants - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: assistantsService.getAllAssistants - ${getErrorMessage(error)}` + ) } } @@ -218,15 +198,14 @@ const getAssistantById = async (assistantId: string): Promise => { id: assistantId }) if (!dbResponse) { - return { - executionError: true, - status: 404, - msg: `Assistant ${assistantId} not found` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Assistant ${assistantId} not found`) } return dbResponse } catch (error) { - throw new Error(`Error: assistantsService.getAssistantById - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: assistantsService.getAssistantById - ${getErrorMessage(error)}` + ) } } @@ -238,11 +217,7 @@ const updateAssistant = async (assistantId: string, requestBody: any): Promise) => { @@ -16,7 +19,10 @@ const createChatMessage = async (chatMessage: Partial) => { const dbResponse = await utilAddChatMessage(chatMessage) return dbResponse } catch (error) { - throw new Error(`Error: chatMessagesService.createChatMessage - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: chatMessagesService.createChatMessage - ${getErrorMessage(error)}` + ) } } @@ -48,7 +54,10 @@ const getAllChatMessages = async ( ) return dbResponse } catch (error) { - throw new Error(`Error: chatMessagesService.getAllChatMessages - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: chatMessagesService.getAllChatMessages - ${getErrorMessage(error)}` + ) } } @@ -80,7 +89,10 @@ const getAllInternalChatMessages = async ( ) return dbResponse } catch (error) { - throw new Error(`Error: chatMessagesService.getAllInternalChatMessages - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: chatMessagesService.getAllInternalChatMessages - ${getErrorMessage(error)}` + ) } } @@ -104,7 +116,10 @@ const removeAllChatMessages = async (chatId: string, chatflowid: string, deleteO const dbResponse = await appServer.AppDataSource.getRepository(ChatMessage).delete(deleteOptions) return dbResponse } catch (error) { - throw new Error(`Error: chatMessagesService.removeAllChatMessages - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: chatMessagesService.removeAllChatMessages - ${getErrorMessage(error)}` + ) } } diff --git a/packages/server/src/services/chatflows/index.ts b/packages/server/src/services/chatflows/index.ts index 2bf71c94..58bbfbb1 100644 --- a/packages/server/src/services/chatflows/index.ts +++ b/packages/server/src/services/chatflows/index.ts @@ -1,4 +1,6 @@ import path from 'path' +import { StatusCodes } from 'http-status-codes' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' import { getRunningExpressApp } from '../../utils/getRunningExpressApp' import { IChatFlow } from '../../Interface' import { ChatFlow } from '../../database/entities/ChatFlow' @@ -18,6 +20,7 @@ import { ChatMessage } from '../../database/entities/ChatMessage' import { ChatMessageFeedback } from '../../database/entities/ChatMessageFeedback' import { UpsertHistory } from '../../database/entities/UpsertHistory' import { containsBase64File, updateFlowDataWithFilePaths } from '../../utils/fileRepository' +import { getErrorMessage } from '../../errors/utils' // Check if chatflow valid for streaming const checkIfChatflowIsValidForStreaming = async (chatflowId: string): Promise => { @@ -28,11 +31,7 @@ const checkIfChatflowIsValidForStreaming = async (chatflowId: string): Promise endingNodeIds.includes(nd.id)) @@ -59,11 +54,7 @@ const checkIfChatflowIsValidForStreaming = async (chatflowId: string): Promise => { } return dbResponse } catch (error) { - throw new Error(`Error: chatflowsService.getAllChatflows - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: chatflowsService.deleteChatflow - ${getErrorMessage(error)}` + ) } } @@ -136,7 +132,10 @@ const getAllChatflows = async (): Promise => { const dbResponse = await appServer.AppDataSource.getRepository(ChatFlow).find() return dbResponse } catch (error) { - throw new Error(`Error: chatflowsService.getAllChatflows - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: chatflowsService.getAllChatflows - ${getErrorMessage(error)}` + ) } } @@ -151,15 +150,14 @@ const getChatflowByApiKey = async (apiKeyId: string): Promise => { .orderBy('cf.name', 'ASC') .getMany() if (dbResponse.length < 1) { - return { - executionError: true, - status: 404, - msg: `Chatflow not found in the database!` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Chatflow not found in the database!`) } return dbResponse } catch (error) { - throw new Error(`Error: chatflowsService.getChatflowByApiKey - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: chatflowsService.getChatflowByApiKey - ${getErrorMessage(error)}` + ) } } @@ -170,15 +168,14 @@ const getChatflowById = async (chatflowId: string): Promise => { id: chatflowId }) if (!dbResponse) { - return { - executionError: true, - status: 404, - msg: `Chatflow ${chatflowId} not found in the database!` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Chatflow ${chatflowId} not found in the database!`) } return dbResponse } catch (error) { - throw new Error(`Error: chatflowsService.getAllChatflows - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: chatflowsService.getChatflowById - ${getErrorMessage(error)}` + ) } } @@ -210,7 +207,10 @@ const saveChatflow = async (newChatFlow: ChatFlow): Promise => { }) return dbResponse } catch (error) { - throw new Error(`Error: chatflowsService.saveChatflow - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: chatflowsService.saveChatflow - ${getErrorMessage(error)}` + ) } } @@ -231,7 +231,10 @@ const updateChatflow = async (chatflow: ChatFlow, updateChatFlow: ChatFlow): Pro } return dbResponse } catch (error) { - throw new Error(`Error: chatflowsService.updateChatflow - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: chatflowsService.updateChatflow - ${getErrorMessage(error)}` + ) } } @@ -245,19 +248,14 @@ const getSinglePublicChatflow = async (chatflowId: string): Promise => { if (dbResponse && dbResponse.isPublic) { return dbResponse } else if (dbResponse && !dbResponse.isPublic) { - return { - executionError: true, - status: 401, - msg: `Unauthorized` - } - } - return { - executionError: true, - status: 404, - msg: `Chatflow ${chatflowId} not found` + throw new InternalFlowiseError(StatusCodes.UNAUTHORIZED, `Unauthorized`) } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Chatflow ${chatflowId} not found`) } catch (error) { - throw new Error(`Error: chatflowsService.getSinglePublicChatflow - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: chatflowsService.getSinglePublicChatflow - ${getErrorMessage(error)}` + ) } } @@ -270,11 +268,7 @@ const getSinglePublicChatbotConfig = async (chatflowId: string): Promise => id: chatflowId }) if (!dbResponse) { - return { - executionError: true, - status: 404, - msg: `Chatflow ${chatflowId} not found` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Chatflow ${chatflowId} not found`) } const uploadsConfig = await utilGetUploadsConfig(chatflowId) // even if chatbotConfig is not set but uploads are enabled @@ -284,16 +278,15 @@ const getSinglePublicChatbotConfig = async (chatflowId: string): Promise => const parsedConfig = dbResponse.chatbotConfig ? JSON.parse(dbResponse.chatbotConfig) : {} return { ...parsedConfig, uploads: uploadsConfig } } catch (e) { - return { - executionError: true, - status: 500, - msg: `Error parsing Chatbot Config for Chatflow ${chatflowId}` - } + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Error parsing Chatbot Config for Chatflow ${chatflowId}`) } } return 'OK' } catch (error) { - throw new Error(`Error: chatflowsService.getSinglePublicChatbotConfig - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: chatflowsService.getSinglePublicChatbotConfig - ${getErrorMessage(error)}` + ) } } diff --git a/packages/server/src/services/components-credentials/index.ts b/packages/server/src/services/components-credentials/index.ts index bbc4128a..c65295b9 100644 --- a/packages/server/src/services/components-credentials/index.ts +++ b/packages/server/src/services/components-credentials/index.ts @@ -1,5 +1,8 @@ import { cloneDeep } from 'lodash' +import { StatusCodes } from 'http-status-codes' import { getRunningExpressApp } from '../../utils/getRunningExpressApp' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { getErrorMessage } from '../../errors/utils' // Get all component credentials const getAllComponentsCredentials = async (): Promise => { @@ -12,7 +15,10 @@ const getAllComponentsCredentials = async (): Promise => { } return dbResponse } catch (error) { - throw new Error(`Error: componentsCredentialsService.getAllComponentsCredentials - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: componentsCredentialsService.getAllComponentsCredentials - ${getErrorMessage(error)}` + ) } } @@ -23,7 +29,8 @@ const getComponentByName = async (credentialName: string) => { if (Object.prototype.hasOwnProperty.call(appServer.nodesPool.componentCredentials, credentialName)) { return appServer.nodesPool.componentCredentials[credentialName] } else { - throw new Error( + throw new InternalFlowiseError( + StatusCodes.NOT_FOUND, `Error: componentsCredentialsService.getSingleComponentsCredential - Credential ${credentialName} not found` ) } @@ -33,13 +40,19 @@ const getComponentByName = async (credentialName: string) => { if (Object.prototype.hasOwnProperty.call(appServer.nodesPool.componentCredentials, name)) { dbResponse.push(appServer.nodesPool.componentCredentials[name]) } else { - throw new Error(`Error: componentsCredentialsService.getSingleComponentsCredential - Credential ${name} not found`) + throw new InternalFlowiseError( + StatusCodes.NOT_FOUND, + `Error: componentsCredentialsService.getSingleComponentsCredential - Credential ${name} not found` + ) } } return dbResponse } } catch (error) { - throw new Error(`Error: componentsCredentialsService.getSingleComponentsCredential - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: componentsCredentialsService.getSingleComponentsCredential - ${getErrorMessage(error)}` + ) } } @@ -50,20 +63,23 @@ const getSingleComponentsCredentialIcon = async (credentialName: string) => { if (Object.prototype.hasOwnProperty.call(appServer.nodesPool.componentCredentials, credentialName)) { const credInstance = appServer.nodesPool.componentCredentials[credentialName] if (credInstance.icon === undefined) { - throw new Error(`Credential ${credentialName} icon not found`) + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Credential ${credentialName} icon not found`) } if (credInstance.icon.endsWith('.svg') || credInstance.icon.endsWith('.png') || credInstance.icon.endsWith('.jpg')) { const filepath = credInstance.icon return filepath } else { - throw new Error(`Credential ${credentialName} icon is missing icon`) + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Credential ${credentialName} icon is missing icon`) } } else { - throw new Error(`Credential ${credentialName} not found`) + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Credential ${credentialName} not found`) } } catch (error) { - throw new Error(`Error: componentsCredentialsService.getSingleComponentsCredentialIcon - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: componentsCredentialsService.getSingleComponentsCredentialIcon - ${getErrorMessage(error)}` + ) } } diff --git a/packages/server/src/services/credentials/index.ts b/packages/server/src/services/credentials/index.ts index 5c5d145e..eed2eed0 100644 --- a/packages/server/src/services/credentials/index.ts +++ b/packages/server/src/services/credentials/index.ts @@ -1,8 +1,11 @@ import { omit } from 'lodash' +import { StatusCodes } from 'http-status-codes' import { getRunningExpressApp } from '../../utils/getRunningExpressApp' import { Credential } from '../../database/entities/Credential' import { transformToCredentialEntity, decryptCredentialData } from '../../utils' import { ICredentialReturnResponse } from '../../Interface' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { getErrorMessage } from '../../errors/utils' const createCredential = async (requestBody: any) => { try { @@ -12,7 +15,10 @@ const createCredential = async (requestBody: any) => { const dbResponse = await appServer.AppDataSource.getRepository(Credential).save(credential) return dbResponse } catch (error) { - throw new Error(`Error: credentialsService.createCredential - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: credentialsService.createCredential - ${getErrorMessage(error)}` + ) } } @@ -22,15 +28,14 @@ const deleteCredentials = async (credentialId: string): Promise => { const appServer = getRunningExpressApp() const dbResponse = await appServer.AppDataSource.getRepository(Credential).delete({ id: credentialId }) if (!dbResponse) { - return { - executionError: true, - status: 404, - msg: `Credential ${credentialId} not found` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Credential ${credentialId} not found`) } return dbResponse } catch (error) { - throw new Error(`Error: credentialsService.deleteCredential - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: credentialsService.deleteCredential - ${getErrorMessage(error)}` + ) } } @@ -61,7 +66,10 @@ const getAllCredentials = async (paramCredentialName: any) => { } return dbResponse } catch (error) { - throw new Error(`Error: credentialsService.getAllCredentials - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: credentialsService.getAllCredentials - ${getErrorMessage(error)}` + ) } } @@ -72,11 +80,7 @@ const getCredentialById = async (credentialId: string): Promise => { id: credentialId }) if (!credential) { - return { - executionError: true, - status: 404, - msg: `Credential ${credentialId} not found` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Credential ${credentialId} not found`) } // Decrpyt credentialData const decryptedCredentialData = await decryptCredentialData( @@ -91,7 +95,10 @@ const getCredentialById = async (credentialId: string): Promise => { const dbResponse = omit(returnCredential, ['encryptedData']) return dbResponse } catch (error) { - throw new Error(`Error: credentialsService.createCredential - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: credentialsService.createCredential - ${getErrorMessage(error)}` + ) } } @@ -102,18 +109,17 @@ const updateCredential = async (credentialId: string, requestBody: any): Promise id: credentialId }) if (!credential) { - return { - executionError: true, - status: 404, - msg: `Credential ${credentialId} not found` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Credential ${credentialId} not found`) } const updateCredential = await transformToCredentialEntity(requestBody) await appServer.AppDataSource.getRepository(Credential).merge(credential, updateCredential) const dbResponse = await appServer.AppDataSource.getRepository(Credential).save(credential) return dbResponse } catch (error) { - throw new Error(`Error: credentialsService.updateCredential - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: credentialsService.updateCredential - ${getErrorMessage(error)}` + ) } } diff --git a/packages/server/src/services/feedback/index.ts b/packages/server/src/services/feedback/index.ts index 9084be61..df6bc49c 100644 --- a/packages/server/src/services/feedback/index.ts +++ b/packages/server/src/services/feedback/index.ts @@ -1,7 +1,10 @@ +import { StatusCodes } from 'http-status-codes' import { utilGetChatMessageFeedback } from '../../utils/getChatMessageFeedback' import { utilAddChatMessageFeedback } from '../../utils/addChatMessageFeedback' import { utilUpdateChatMessageFeedback } from '../../utils/updateChatMessageFeedback' import { IChatMessageFeedback } from '../../Interface' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { getErrorMessage } from '../../errors/utils' // Get all chatmessage feedback from chatflowid const getAllChatMessageFeedback = async ( @@ -15,7 +18,10 @@ const getAllChatMessageFeedback = async ( const dbResponse = await utilGetChatMessageFeedback(chatflowid, chatId, sortOrder, startDate, endDate) return dbResponse } catch (error) { - throw new Error(`Error: feedbackService.getAllChatMessageFeedback - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: feedbackService.getAllChatMessageFeedback - ${getErrorMessage(error)}` + ) } } @@ -25,7 +31,10 @@ const createChatMessageFeedbackForChatflow = async (requestBody: Partial => { try { const url = decodeURIComponent(requestUrl) if (!relativeLinksMethod) { - return { - executionError: true, - status: 500, - msg: `Please choose a Relative Links Method in Additional Parameters!` - } + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Please choose a Relative Links Method in Additional Parameters!` + ) } const limit = parseInt(queryLimit) if (process.env.DEBUG === 'true') console.info(`Start ${relativeLinksMethod}`) @@ -20,7 +22,10 @@ const getAllLinks = async (requestUrl: string, relativeLinksMethod: string, quer } return dbResponse } catch (error) { - throw new Error(`Error: fetchLinksService.getAllLinks - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: fetchLinksService.getAllLinks - ${getErrorMessage(error)}` + ) } } diff --git a/packages/server/src/services/flow-configs/index.ts b/packages/server/src/services/flow-configs/index.ts index 8dbcd6d3..8ce05499 100644 --- a/packages/server/src/services/flow-configs/index.ts +++ b/packages/server/src/services/flow-configs/index.ts @@ -1,18 +1,17 @@ +import { StatusCodes } from 'http-status-codes' import { findAvailableConfigs } from '../../utils' import { IReactFlowObject } from '../../Interface' import { getRunningExpressApp } from '../../utils/getRunningExpressApp' import chatflowsService from '../chatflows' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { getErrorMessage } from '../../errors/utils' const getSingleFlowConfig = async (chatflowId: string): Promise => { try { const appServer = getRunningExpressApp() const chatflow = await chatflowsService.getChatflowById(chatflowId) if (!chatflow) { - return { - executionError: true, - status: 404, - msg: `Chatflow ${chatflowId} not found in the database!` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Chatflow ${chatflowId} not found in the database!`) } const flowData = chatflow.flowData const parsedFlowData: IReactFlowObject = JSON.parse(flowData) @@ -20,7 +19,10 @@ const getSingleFlowConfig = async (chatflowId: string): Promise => { const dbResponse = findAvailableConfigs(nodes, appServer.nodesPool.componentCredentials) return dbResponse } catch (error) { - throw new Error(`Error: flowConfigService.getSingleFlowConfig - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: flowConfigService.getSingleFlowConfig - ${getErrorMessage(error)}` + ) } } diff --git a/packages/server/src/services/load-prompts/index.ts b/packages/server/src/services/load-prompts/index.ts index 0cdc3ffb..5f041a83 100644 --- a/packages/server/src/services/load-prompts/index.ts +++ b/packages/server/src/services/load-prompts/index.ts @@ -1,5 +1,8 @@ import { Client } from 'langchainhub' +import { StatusCodes } from 'http-status-codes' import { parsePrompt } from '../../utils/hub' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { getErrorMessage } from '../../errors/utils' const createPrompt = async (promptName: string): Promise => { try { @@ -13,7 +16,10 @@ const createPrompt = async (promptName: string): Promise => { } return dbResponse } catch (error) { - throw new Error(`Error: loadPromptsService.createPrompt - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: loadPromptsService.createPrompt - ${getErrorMessage(error)}` + ) } } diff --git a/packages/server/src/services/marketplaces/index.ts b/packages/server/src/services/marketplaces/index.ts index 218452dd..54e43899 100644 --- a/packages/server/src/services/marketplaces/index.ts +++ b/packages/server/src/services/marketplaces/index.ts @@ -1,5 +1,8 @@ import path from 'path' import * as fs from 'fs' +import { StatusCodes } from 'http-status-codes' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { getErrorMessage } from '../../errors/utils' // Get all templates for marketplaces const getAllTemplates = async () => { @@ -49,7 +52,10 @@ const getAllTemplates = async () => { const dbResponse = sortedTemplates return dbResponse } catch (error) { - throw new Error(`Error: marketplacesService.getAllTemplates - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: marketplacesService.getAllTemplates - ${getErrorMessage(error)}` + ) } } diff --git a/packages/server/src/services/node-configs/index.ts b/packages/server/src/services/node-configs/index.ts index 7eb523e8..0debdc5e 100644 --- a/packages/server/src/services/node-configs/index.ts +++ b/packages/server/src/services/node-configs/index.ts @@ -1,6 +1,9 @@ +import { StatusCodes } from 'http-status-codes' import { findAvailableConfigs } from '../../utils' import { IReactFlowNode } from '../../Interface' import { getRunningExpressApp } from '../../utils/getRunningExpressApp' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { getErrorMessage } from '../../errors/utils' const getAllNodeConfigs = async (requestBody: any) => { try { @@ -9,7 +12,10 @@ const getAllNodeConfigs = async (requestBody: any) => { const dbResponse = findAvailableConfigs(nodes, appServer.nodesPool.componentCredentials) return dbResponse } catch (error) { - throw new Error(`Error: nodeConfigsService.getAllNodeConfigs - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: nodeConfigsService.getAllNodeConfigs - ${getErrorMessage(error)}` + ) } } diff --git a/packages/server/src/services/nodes/index.ts b/packages/server/src/services/nodes/index.ts index 0bf097b4..715740e2 100644 --- a/packages/server/src/services/nodes/index.ts +++ b/packages/server/src/services/nodes/index.ts @@ -1,9 +1,12 @@ import { cloneDeep } from 'lodash' +import { StatusCodes } from 'http-status-codes' import { getRunningExpressApp } from '../../utils/getRunningExpressApp' import { INodeData } from '../../Interface' import { INodeOptionsValue, ICommonObject, handleEscapeCharacters } from 'flowise-components' import { databaseEntities } from '../../utils' import logger from '../../utils/logger' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { getErrorMessage } from '../../errors/utils' // Get all component nodes const getAllNodes = async () => { @@ -16,7 +19,7 @@ const getAllNodes = async () => { } return dbResponse } catch (error) { - throw new Error(`Error: nodesService.getAllNodes - ${error}`) + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Error: nodesService.getAllNodes - ${getErrorMessage(error)}`) } } @@ -28,10 +31,10 @@ const getNodeByName = async (nodeName: string) => { const dbResponse = appServer.nodesPool.componentNodes[nodeName] return dbResponse } else { - throw new Error(`Node ${nodeName} not found`) + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Node ${nodeName} not found`) } } catch (error) { - throw new Error(`Error: nodesService.getAllNodes - ${error}`) + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Error: nodesService.getAllNodes - ${getErrorMessage(error)}`) } } @@ -42,20 +45,23 @@ const getSingleNodeIcon = async (nodeName: string) => { if (Object.prototype.hasOwnProperty.call(appServer.nodesPool.componentNodes, nodeName)) { const nodeInstance = appServer.nodesPool.componentNodes[nodeName] if (nodeInstance.icon === undefined) { - throw new Error(`Node ${nodeName} icon not found`) + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Node ${nodeName} icon not found`) } if (nodeInstance.icon.endsWith('.svg') || nodeInstance.icon.endsWith('.png') || nodeInstance.icon.endsWith('.jpg')) { const filepath = nodeInstance.icon return filepath } else { - throw new Error(`Node ${nodeName} icon is missing icon`) + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Node ${nodeName} icon is missing icon`) } } else { - throw new Error(`Node ${nodeName} not found`) + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Node ${nodeName} not found`) } } catch (error) { - throw new Error(`Error: nodesService.getSingleNodeIcon - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: nodesService.getSingleNodeIcon - ${getErrorMessage(error)}` + ) } } @@ -78,14 +84,13 @@ const getSingleNodeAsyncOptions = async (nodeName: string, requestBody: any): Pr return [] } } else { - return { - executionError: true, - status: 404, - msg: `Node ${nodeName} not found` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Node ${nodeName} not found`) } } catch (error) { - throw new Error(`Error: nodesService.getSingleNodeAsyncOptions - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: nodesService.getSingleNodeAsyncOptions - ${getErrorMessage(error)}` + ) } } @@ -115,21 +120,16 @@ const executeCustomFunction = async (requestBody: any) => { return dbResponse } catch (error) { - return { - executionError: true, - status: 500, - msg: `Error running custom function: ${error}` - } + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Error running custom function: ${error}`) } } else { - return { - executionError: true, - status: 404, - msg: `Node customFunction not found` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Node customFunction not found`) } } catch (error) { - throw new Error(`Error: nodesService.executeCustomFunction - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: nodesService.executeCustomFunction - ${getErrorMessage(error)}` + ) } } diff --git a/packages/server/src/services/openai-assistants/index.ts b/packages/server/src/services/openai-assistants/index.ts index cffa2e3f..00ea5e60 100644 --- a/packages/server/src/services/openai-assistants/index.ts +++ b/packages/server/src/services/openai-assistants/index.ts @@ -1,7 +1,10 @@ import OpenAI from 'openai' +import { StatusCodes } from 'http-status-codes' import { decryptCredentialData } from '../../utils' import { getRunningExpressApp } from '../../utils/getRunningExpressApp' import { Credential } from '../../database/entities/Credential' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { getErrorMessage } from '../../errors/utils' // ---------------------------------------- // Assistants @@ -15,28 +18,23 @@ const getAllOpenaiAssistants = async (credentialId: string): Promise => { id: credentialId }) if (!credential) { - return { - executionError: true, - status: 404, - msg: `Credential ${credentialId} not found in the database!` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Credential ${credentialId} not found in the database!`) } // Decrpyt credentialData const decryptedCredentialData = await decryptCredentialData(credential.encryptedData) const openAIApiKey = decryptedCredentialData['openAIApiKey'] if (!openAIApiKey) { - return { - executionError: true, - status: 404, - msg: `OpenAI ApiKey not found` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `OpenAI ApiKey not found`) } const openai = new OpenAI({ apiKey: openAIApiKey }) const retrievedAssistants = await openai.beta.assistants.list() const dbResponse = retrievedAssistants.data return dbResponse } catch (error) { - throw new Error(`Error: openaiAssistantsService.getAllOpenaiAssistants - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: openaiAssistantsService.getAllOpenaiAssistants - ${getErrorMessage(error)}` + ) } } @@ -48,21 +46,13 @@ const getSingleOpenaiAssistant = async (credentialId: string, assistantId: strin id: credentialId }) if (!credential) { - return { - executionError: true, - status: 404, - msg: `Credential ${credentialId} not found in the database!` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Credential ${credentialId} not found in the database!`) } // Decrpyt credentialData const decryptedCredentialData = await decryptCredentialData(credential.encryptedData) const openAIApiKey = decryptedCredentialData['openAIApiKey'] if (!openAIApiKey) { - return { - executionError: true, - status: 404, - msg: `OpenAI ApiKey not found` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `OpenAI ApiKey not found`) } const openai = new OpenAI({ apiKey: openAIApiKey }) @@ -74,7 +64,10 @@ const getSingleOpenaiAssistant = async (credentialId: string, assistantId: strin } return dbResponse } catch (error) { - throw new Error(`Error: openaiAssistantsService.getSingleOpenaiAssistant - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: openaiAssistantsService.getSingleOpenaiAssistant - ${getErrorMessage(error)}` + ) } } diff --git a/packages/server/src/services/predictions/index.ts b/packages/server/src/services/predictions/index.ts new file mode 100644 index 00000000..e7411fe6 --- /dev/null +++ b/packages/server/src/services/predictions/index.ts @@ -0,0 +1,22 @@ +import { Request } from 'express' +import { Server } from 'socket.io' +import { StatusCodes } from 'http-status-codes' +import { utilBuildChatflow } from '../../utils/buildChatflow' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { getErrorMessage } from '../../errors/utils' + +const buildChatflow = async (fullRequest: Request, ioServer: Server) => { + try { + const dbResponse = await utilBuildChatflow(fullRequest, ioServer) + return dbResponse + } catch (error) { + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: predictionsServices.buildChatflow - ${getErrorMessage(error)}` + ) + } +} + +export default { + buildChatflow +} diff --git a/packages/server/src/services/stats/index.ts b/packages/server/src/services/stats/index.ts index 2f2448a1..2f6faff2 100644 --- a/packages/server/src/services/stats/index.ts +++ b/packages/server/src/services/stats/index.ts @@ -1,7 +1,10 @@ +import { StatusCodes } from 'http-status-codes' import { chatType } from '../../Interface' import { ChatMessage } from '../../database/entities/ChatMessage' import { utilGetChatMessage } from '../../utils/getChatMessage' import { ChatMessageFeedback } from '../../database/entities/ChatMessageFeedback' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { getErrorMessage } from '../../errors/utils' // get stats for showing in chatflow const getChatflowStats = async ( @@ -36,7 +39,10 @@ const getChatflowStats = async ( return dbResponse } catch (error) { - throw new Error(`Error: statsService.getChatflowStats - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: statsService.getChatflowStats - ${getErrorMessage(error)}` + ) } } diff --git a/packages/server/src/services/tools/index.ts b/packages/server/src/services/tools/index.ts index 42a579e1..f2e41400 100644 --- a/packages/server/src/services/tools/index.ts +++ b/packages/server/src/services/tools/index.ts @@ -1,8 +1,11 @@ +import { StatusCodes } from 'http-status-codes' import { getRunningExpressApp } from '../../utils/getRunningExpressApp' import { Tool } from '../../database/entities/Tool' import { getAppVersion } from '../../utils' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { getErrorMessage } from '../../errors/utils' -const creatTool = async (requestBody: any): Promise => { +const createTool = async (requestBody: any): Promise => { try { const appServer = getRunningExpressApp() const newTool = new Tool() @@ -16,7 +19,7 @@ const creatTool = async (requestBody: any): Promise => { }) return dbResponse } catch (error) { - throw new Error(`Error: toolsService.creatTool - ${error}`) + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Error: toolsService.createTool - ${getErrorMessage(error)}`) } } @@ -28,7 +31,7 @@ const deleteTool = async (toolId: string): Promise => { }) return dbResponse } catch (error) { - throw new Error(`Error: toolsService.deleteTool - ${error}`) + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Error: toolsService.deleteTool - ${getErrorMessage(error)}`) } } @@ -38,7 +41,7 @@ const getAllTools = async (): Promise => { const dbResponse = await appServer.AppDataSource.getRepository(Tool).find() return dbResponse } catch (error) { - throw new Error(`Error: toolsService.getAllTools - ${error}`) + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Error: toolsService.getAllTools - ${getErrorMessage(error)}`) } } @@ -49,15 +52,11 @@ const getToolById = async (toolId: string): Promise => { id: toolId }) if (!dbResponse) { - return { - executionError: true, - status: 404, - msg: `Tool ${toolId} not found` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Tool ${toolId} not found`) } return dbResponse } catch (error) { - throw new Error(`Error: toolsService.getToolById - ${error}`) + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Error: toolsService.getToolById - ${getErrorMessage(error)}`) } } @@ -68,11 +67,7 @@ const updateTool = async (toolId: string, toolBody: any): Promise => { id: toolId }) if (!tool) { - return { - executionError: true, - status: 404, - msg: `Tool ${toolId} not found` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Tool ${toolId} not found`) } const updateTool = new Tool() Object.assign(updateTool, toolBody) @@ -80,12 +75,12 @@ const updateTool = async (toolId: string, toolBody: any): Promise => { const dbResponse = await appServer.AppDataSource.getRepository(Tool).save(tool) return dbResponse } catch (error) { - throw new Error(`Error: toolsService.getToolById - ${error}`) + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Error: toolsService.updateTool - ${getErrorMessage(error)}`) } } export default { - creatTool, + createTool, deleteTool, getAllTools, getToolById, diff --git a/packages/server/src/services/upsert-history/index.ts b/packages/server/src/services/upsert-history/index.ts index 96d9d82d..72e484b1 100644 --- a/packages/server/src/services/upsert-history/index.ts +++ b/packages/server/src/services/upsert-history/index.ts @@ -1,6 +1,9 @@ import { MoreThanOrEqual, LessThanOrEqual } from 'typeorm' +import { StatusCodes } from 'http-status-codes' import { getRunningExpressApp } from '../../utils/getRunningExpressApp' import { UpsertHistory } from '../../database/entities/UpsertHistory' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { getErrorMessage } from '../../errors/utils' const getAllUpsertHistory = async ( sortOrder: string | undefined, @@ -46,7 +49,10 @@ const getAllUpsertHistory = async ( return upsertHistory } catch (error) { - throw new Error(`Error: upsertHistoryServices.getAllUpsertHistory - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: upsertHistoryServices.getAllUpsertHistory - ${getErrorMessage(error)}` + ) } } @@ -56,7 +62,10 @@ const patchDeleteUpsertHistory = async (ids: string[] = []): Promise => { const dbResponse = await appServer.AppDataSource.getRepository(UpsertHistory).delete(ids) return dbResponse } catch (error) { - throw new Error(`Error: upsertHistoryServices.patchUpsertHistory - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: upsertHistoryServices.patchDeleteUpsertHistory - ${getErrorMessage(error)}` + ) } } diff --git a/packages/server/src/services/variables/index.ts b/packages/server/src/services/variables/index.ts index 37e1c073..d2377dc2 100644 --- a/packages/server/src/services/variables/index.ts +++ b/packages/server/src/services/variables/index.ts @@ -1,5 +1,8 @@ +import { StatusCodes } from 'http-status-codes' import { getRunningExpressApp } from '../../utils/getRunningExpressApp' import { Variable } from '../../database/entities/Variable' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { getErrorMessage } from '../../errors/utils' const createVariable = async (newVariable: Variable) => { try { @@ -8,7 +11,10 @@ const createVariable = async (newVariable: Variable) => { const dbResponse = await appServer.AppDataSource.getRepository(Variable).save(variable) return dbResponse } catch (error) { - throw new Error(`Error: variablesServices.createVariable - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: variablesServices.createVariable - ${getErrorMessage(error)}` + ) } } @@ -18,7 +24,10 @@ const deleteVariable = async (variableId: string): Promise => { const dbResponse = await appServer.AppDataSource.getRepository(Variable).delete({ id: variableId }) return dbResponse } catch (error) { - throw new Error(`Error: variablesServices.deleteVariable - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: variablesServices.deleteVariable - ${getErrorMessage(error)}` + ) } } @@ -28,7 +37,10 @@ const getAllVariables = async () => { const dbResponse = await appServer.AppDataSource.getRepository(Variable).find() return dbResponse } catch (error) { - throw new Error(`Error: variablesServices.getAllVariables - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: variablesServices.getAllVariables - ${getErrorMessage(error)}` + ) } } @@ -40,7 +52,10 @@ const getVariableById = async (variableId: string) => { }) return dbResponse } catch (error) { - throw new Error(`Error: variablesServices.getVariableById - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: variablesServices.getVariableById - ${getErrorMessage(error)}` + ) } } @@ -51,7 +66,10 @@ const updateVariable = async (variable: Variable, updatedVariable: Variable) => const dbResponse = await appServer.AppDataSource.getRepository(Variable).save(tmpUpdatedVariable) return dbResponse } catch (error) { - throw new Error(`Error: variablesServices.updateVariable - ${error}`) + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Error: variablesServices.updateVariable - ${getErrorMessage(error)}` + ) } } diff --git a/packages/server/src/services/vectors/index.ts b/packages/server/src/services/vectors/index.ts index 7c55a510..15892f57 100644 --- a/packages/server/src/services/vectors/index.ts +++ b/packages/server/src/services/vectors/index.ts @@ -1,11 +1,14 @@ -import { Request, Response } from 'express' +import { Request } from 'express' +import { StatusCodes } from 'http-status-codes' import { upsertVector } from '../../utils/upsertVector' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { getErrorMessage } from '../../errors/utils' -const upsertVectorMiddleware = async (req: Request, res: Response, isInternal: boolean = false) => { +const upsertVectorMiddleware = async (req: Request, isInternal: boolean = false) => { try { - await upsertVector(req, res, isInternal) + return await upsertVector(req, isInternal) } catch (error) { - throw new Error(`Error: vectorsService.getRateLimiter - ${error}`) + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Error: vectorsService.upsertVector - ${getErrorMessage(error)}`) } } diff --git a/packages/server/src/services/versions/index.ts b/packages/server/src/services/versions/index.ts index 391cdb1b..f8300603 100644 --- a/packages/server/src/services/versions/index.ts +++ b/packages/server/src/services/versions/index.ts @@ -1,5 +1,8 @@ import path from 'path' import * as fs from 'fs' +import { StatusCodes } from 'http-status-codes' +import { InternalFlowiseError } from '../../errors/internalFlowiseError' +import { getErrorMessage } from '../../errors/utils' const getVersion = async () => { try { @@ -20,11 +23,7 @@ const getVersion = async () => { } const packagejsonPath = getPackageJsonPath() if (!packagejsonPath) { - return { - executionError: true, - status: 404, - msg: 'Version not found' - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Version not found`) } try { const content = await fs.promises.readFile(packagejsonPath, 'utf8') @@ -33,14 +32,10 @@ const getVersion = async () => { version: parsedContent.version } } catch (error) { - return { - executionError: true, - status: 500, - msg: `Version not found: ${error}` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Version not found- ${getErrorMessage(error)}`) } } catch (error) { - throw new Error(`Error: versionService.getVersion - ${error}`) + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Error: versionService.getVersion - ${getErrorMessage(error)}`) } } diff --git a/packages/server/src/utils/addChatflowsCount.ts b/packages/server/src/utils/addChatflowsCount.ts index c0ee664a..ede05121 100644 --- a/packages/server/src/utils/addChatflowsCount.ts +++ b/packages/server/src/utils/addChatflowsCount.ts @@ -1,5 +1,8 @@ +import { StatusCodes } from 'http-status-codes' import { ChatFlow } from '../database/entities/ChatFlow' +import { InternalFlowiseError } from '../errors/internalFlowiseError' import { getRunningExpressApp } from '../utils/getRunningExpressApp' +import { getErrorMessage } from '../errors/utils' export const addChatflowsCount = async (keys: any) => { try { @@ -28,6 +31,6 @@ export const addChatflowsCount = async (keys: any) => { } return tmpResult } catch (error) { - throw new Error(`Error: addChatflowsCount - ${error}`) + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Error: addChatflowsCount - ${getErrorMessage(error)}`) } } diff --git a/packages/server/src/utils/buildChatflow.ts b/packages/server/src/utils/buildChatflow.ts index b1043cc4..16cdd88c 100644 --- a/packages/server/src/utils/buildChatflow.ts +++ b/packages/server/src/utils/buildChatflow.ts @@ -3,6 +3,7 @@ import { IFileUpload, getStoragePath, convertSpeechToText, ICommonObject } from import { StatusCodes } from 'http-status-codes' import { IncomingInput, IMessage, INodeData, IReactFlowObject, IReactFlowNode, IDepthQueue, chatType, IChatMessage } from '../Interface' import path from 'path' +import { InternalFlowiseError } from '../errors/internalFlowiseError' import { ChatFlow } from '../database/entities/ChatFlow' import { Server } from 'socket.io' import { getRunningExpressApp } from '../utils/getRunningExpressApp' @@ -47,11 +48,7 @@ export const utilBuildChatflow = async (req: Request, socketIO?: Server, isInter id: chatflowid }) if (!chatflow) { - return { - executionError: true, - status: StatusCodes.NOT_FOUND, - msg: `Chatflow ${chatflowid} not found` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Chatflow ${chatflowid} not found`) } const chatId = incomingInput.chatId ?? incomingInput.overrideConfig?.sessionId ?? uuidv4() @@ -60,11 +57,7 @@ export const utilBuildChatflow = async (req: Request, socketIO?: Server, isInter if (!isInternal) { const isKeyValidated = await utilValidateKey(req, chatflow) if (!isKeyValidated) { - return { - executionError: true, - status: StatusCodes.UNAUTHORIZED, - msg: `Unauthorized` - } + throw new InternalFlowiseError(StatusCodes.UNAUTHORIZED, `Unauthorized`) } } @@ -189,11 +182,7 @@ export const utilBuildChatflow = async (req: Request, socketIO?: Server, isInter const directedGraph = graph const endingNodeIds = getEndingNodes(nodeDependencies, directedGraph) if (!endingNodeIds.length) { - return { - executionError: true, - status: 500, - msg: `Ending nodes not found` - } + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Ending nodes not found`) } const endingNodes = nodes.filter((nd) => endingNodeIds.includes(nd.id)) @@ -203,11 +192,7 @@ export const utilBuildChatflow = async (req: Request, socketIO?: Server, isInter for (const endingNode of endingNodes) { const endingNodeData = endingNode.data if (!endingNodeData) { - return { - executionError: true, - status: 500, - msg: `Ending node ${endingNode.id} data not found` - } + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Ending node ${endingNode.id} data not found`) } const isEndingNode = endingNodeData?.outputs?.output === 'EndingNode' @@ -219,11 +204,7 @@ export const utilBuildChatflow = async (req: Request, socketIO?: Server, isInter endingNodeData.category !== 'Agents' && endingNodeData.category !== 'Engine' ) { - return { - executionError: true, - status: 500, - msg: `Ending node must be either a Chain or Agent` - } + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Ending node must be either a Chain or Agent`) } if ( @@ -231,11 +212,10 @@ export const utilBuildChatflow = async (req: Request, socketIO?: Server, isInter Object.keys(endingNodeData.outputs).length && !Object.values(endingNodeData.outputs ?? {}).includes(endingNodeData.name) ) { - return { - executionError: true, - status: 500, - msg: `Output of ${endingNodeData.label} (${endingNodeData.id}) must be ${endingNodeData.label}, can't be an Output Prediction` - } + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + `Output of ${endingNodeData.label} (${endingNodeData.id}) must be ${endingNodeData.label}, can't be an Output Prediction` + ) } } @@ -311,11 +291,7 @@ export const utilBuildChatflow = async (req: Request, socketIO?: Server, isInter ? reactFlowNodes.find((node: IReactFlowNode) => endingNodeIds[0] === node.id) : reactFlowNodes[reactFlowNodes.length - 1] if (!nodeToExecute) { - return { - executionError: true, - status: 404, - msg: `Node not found` - } + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Node not found`) } if (incomingInput.overrideConfig) { @@ -417,10 +393,6 @@ export const utilBuildChatflow = async (req: Request, socketIO?: Server, isInter return result } catch (e: any) { logger.error('[server]: Error:', e) - return { - executionError: true, - status: 500, - msg: e.message - } + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, e.message) } } diff --git a/packages/server/src/utils/getUploadsConfig.ts b/packages/server/src/utils/getUploadsConfig.ts index 7be23a6c..bbc5eedd 100644 --- a/packages/server/src/utils/getUploadsConfig.ts +++ b/packages/server/src/utils/getUploadsConfig.ts @@ -1,7 +1,9 @@ +import { StatusCodes } from 'http-status-codes' +import { INodeParams } from 'flowise-components' import { ChatFlow } from '../database/entities/ChatFlow' import { getRunningExpressApp } from '../utils/getRunningExpressApp' import { IUploadFileSizeAndTypes, IReactFlowNode } from '../Interface' -import { INodeParams } from 'flowise-components' +import { InternalFlowiseError } from '../errors/internalFlowiseError' /** * Method that checks if uploads are enabled in the chatflow @@ -12,7 +14,9 @@ export const utilGetUploadsConfig = async (chatflowid: string): Promise => const chatflow = await appServer.AppDataSource.getRepository(ChatFlow).findOneBy({ id: chatflowid }) - if (!chatflow) return `Chatflow ${chatflowid} not found` + if (!chatflow) { + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Chatflow ${chatflowid} not found`) + } const uploadAllowedNodes = ['llmChain', 'conversationChain', 'mrklAgentChat', 'conversationalAgent'] const uploadProcessingNodes = ['chatOpenAI', 'chatAnthropic', 'awsChatBedrock', 'azureChatOpenAI'] diff --git a/packages/server/src/utils/upsertVector.ts b/packages/server/src/utils/upsertVector.ts index d8714502..0913786c 100644 --- a/packages/server/src/utils/upsertVector.ts +++ b/packages/server/src/utils/upsertVector.ts @@ -1,4 +1,4 @@ -import { Request, Response } from 'express' +import { Request } from 'express' import * as fs from 'fs' import { cloneDeep, omit } from 'lodash' import { ICommonObject } from 'flowise-components' @@ -20,14 +20,15 @@ import { IncomingInput, INodeDirectedGraph, IReactFlowObject, chatType } from '. import { ChatFlow } from '../database/entities/ChatFlow' import { getRunningExpressApp } from '../utils/getRunningExpressApp' import { UpsertHistory } from '../database/entities/UpsertHistory' +import { InternalFlowiseError } from '../errors/internalFlowiseError' +import { StatusCodes } from 'http-status-codes' /** * Upsert documents * @param {Request} req - * @param {Response} res * @param {boolean} isInternal */ -export const upsertVector = async (req: Request, res: Response, isInternal: boolean = false) => { +export const upsertVector = async (req: Request, isInternal: boolean = false) => { try { const appServer = getRunningExpressApp() const chatflowid = req.params.id @@ -36,11 +37,15 @@ export const upsertVector = async (req: Request, res: Response, isInternal: bool const chatflow = await appServer.AppDataSource.getRepository(ChatFlow).findOneBy({ id: chatflowid }) - if (!chatflow) return res.status(404).send(`Chatflow ${chatflowid} not found`) + if (!chatflow) { + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Chatflow ${chatflowid} not found`) + } if (!isInternal) { const isKeyValidated = await utilValidateKey(req, chatflow) - if (!isKeyValidated) return res.status(401).send('Unauthorized') + if (!isKeyValidated) { + throw new InternalFlowiseError(StatusCodes.UNAUTHORIZED, `Unauthorized`) + } } const files = (req.files as any[]) || [] @@ -89,11 +94,14 @@ export const upsertVector = async (req: Request, res: Response, isInternal: bool // Check if multiple vector store nodes exist, and if stopNodeId is specified if (vsNodes.length > 1 && !stopNodeId) { - return res.status(500).send('There are multiple vector nodes, please provide stopNodeId in body request') + throw new InternalFlowiseError( + StatusCodes.INTERNAL_SERVER_ERROR, + 'There are multiple vector nodes, please provide stopNodeId in body request' + ) } else if (vsNodes.length === 1 && !stopNodeId) { stopNodeId = vsNodes[0].data.id } else if (!vsNodes.length && !stopNodeId) { - return res.status(500).send('No vector node found') + throw new InternalFlowiseError(StatusCodes.NOT_FOUND, 'No vector node found') } const { graph } = constructGraphs(nodes, edges, { isReversed: true }) @@ -154,9 +162,12 @@ export const upsertVector = async (req: Request, res: Response, isInternal: bool stopNodeId } }) - return res.status(201).json(upsertedResult['result'] ?? { result: 'Successfully Upserted' }) - } catch (e: any) { - logger.error('[server]: Error:', e) - return res.status(500).send(e.message) + + return upsertedResult['result'] ?? { result: 'Successfully Upserted' } + } catch (error) { + logger.error('[server]: Error:', error) + if (error instanceof Error) { + throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, error.message) + } } } diff --git a/packages/ui/src/ui-component/button/FlowListMenu.jsx b/packages/ui/src/ui-component/button/FlowListMenu.jsx index d8023194..9c247b23 100644 --- a/packages/ui/src/ui-component/button/FlowListMenu.jsx +++ b/packages/ui/src/ui-component/button/FlowListMenu.jsx @@ -155,7 +155,7 @@ export default function FlowListMenu({ chatflow, setError, updateFlowsApi }) { } catch (error) { setError(error) enqueueSnackbar({ - message: error.response.data.message, + message: typeof error.response.data === 'object' ? error.response.data.message : error.response.data, options: { key: new Date().getTime() + Math.random(), variant: 'error', @@ -194,7 +194,7 @@ export default function FlowListMenu({ chatflow, setError, updateFlowsApi }) { } catch (error) { setError(error) enqueueSnackbar({ - message: error.response.data.message, + message: typeof error.response.data === 'object' ? error.response.data.message : error.response.data, options: { key: new Date().getTime() + Math.random(), variant: 'error', @@ -226,7 +226,7 @@ export default function FlowListMenu({ chatflow, setError, updateFlowsApi }) { } catch (error) { setError(error) enqueueSnackbar({ - message: error.response.data.message, + message: typeof error.response.data === 'object' ? error.response.data.message : error.response.data, options: { key: new Date().getTime() + Math.random(), variant: 'error', diff --git a/packages/ui/src/ui-component/dialog/ManageScrapedLinksDialog.jsx b/packages/ui/src/ui-component/dialog/ManageScrapedLinksDialog.jsx index ae9869fa..268c0003 100644 --- a/packages/ui/src/ui-component/dialog/ManageScrapedLinksDialog.jsx +++ b/packages/ui/src/ui-component/dialog/ManageScrapedLinksDialog.jsx @@ -83,7 +83,7 @@ const ManageScrapedLinksDialog = ({ show, dialogProps, onCancel, onSave }) => { } } catch (error) { enqueueSnackbar({ - message: error.response.data.message, + message: typeof error.response.data === 'object' ? error.response.data.message : error.response.data, options: { key: new Date().getTime() + Math.random(), variant: 'error', diff --git a/packages/ui/src/ui-component/dialog/ViewMessagesDialog.jsx b/packages/ui/src/ui-component/dialog/ViewMessagesDialog.jsx index fb672e06..6667caf9 100644 --- a/packages/ui/src/ui-component/dialog/ViewMessagesDialog.jsx +++ b/packages/ui/src/ui-component/dialog/ViewMessagesDialog.jsx @@ -262,7 +262,7 @@ const ViewMessagesDialog = ({ show, dialogProps, onCancel }) => { getStatsApi.request(chatflowid) // update stats } catch (error) { enqueueSnackbar({ - message: error.response.data.message, + message: typeof error.response.data === 'object' ? error.response.data.message : error.response.data, options: { key: new Date().getTime() + Math.random(), variant: 'error', diff --git a/packages/ui/src/ui-component/extended/AllowedDomains.jsx b/packages/ui/src/ui-component/extended/AllowedDomains.jsx index 0f37785f..5a5f55b8 100644 --- a/packages/ui/src/ui-component/extended/AllowedDomains.jsx +++ b/packages/ui/src/ui-component/extended/AllowedDomains.jsx @@ -70,7 +70,9 @@ const AllowedDomains = ({ dialogProps }) => { } } catch (error) { enqueueSnackbar({ - message: `Failed to save Allowed Origins: ${error.response.data.message}`, + message: `Failed to save Allowed Origins: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', diff --git a/packages/ui/src/ui-component/extended/AnalyseFlow.jsx b/packages/ui/src/ui-component/extended/AnalyseFlow.jsx index a31bc6bb..6874dc07 100644 --- a/packages/ui/src/ui-component/extended/AnalyseFlow.jsx +++ b/packages/ui/src/ui-component/extended/AnalyseFlow.jsx @@ -145,7 +145,9 @@ const AnalyseFlow = ({ dialogProps }) => { } } catch (error) { enqueueSnackbar({ - message: `Failed to save Analytic Configuration: ${error.response.data.message}`, + message: `Failed to save Analytic Configuration: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', diff --git a/packages/ui/src/ui-component/extended/ChatFeedback.jsx b/packages/ui/src/ui-component/extended/ChatFeedback.jsx index fcebf8f0..ba769b97 100644 --- a/packages/ui/src/ui-component/extended/ChatFeedback.jsx +++ b/packages/ui/src/ui-component/extended/ChatFeedback.jsx @@ -60,7 +60,9 @@ const ChatFeedback = ({ dialogProps }) => { } } catch (error) { enqueueSnackbar({ - message: `Failed to save Chat Feedback Settings: ${error.response.data.message}`, + message: `Failed to save Chat Feedback Settings: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', diff --git a/packages/ui/src/ui-component/extended/RateLimit.jsx b/packages/ui/src/ui-component/extended/RateLimit.jsx index 5ab8532b..3f47667c 100644 --- a/packages/ui/src/ui-component/extended/RateLimit.jsx +++ b/packages/ui/src/ui-component/extended/RateLimit.jsx @@ -74,7 +74,9 @@ const RateLimit = () => { } } catch (error) { enqueueSnackbar({ - message: `Failed to save Rate Limit Configuration: ${error.response.data.message}`, + message: `Failed to save Rate Limit Configuration: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', diff --git a/packages/ui/src/ui-component/extended/SpeechToText.jsx b/packages/ui/src/ui-component/extended/SpeechToText.jsx index ba875544..234840ff 100644 --- a/packages/ui/src/ui-component/extended/SpeechToText.jsx +++ b/packages/ui/src/ui-component/extended/SpeechToText.jsx @@ -113,7 +113,9 @@ const SpeechToText = ({ dialogProps }) => { } } catch (error) { enqueueSnackbar({ - message: `Failed to save Speech To Text Configuration: ${error.response.data.message}`, + message: `Failed to save Speech To Text Configuration: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', diff --git a/packages/ui/src/ui-component/extended/StarterPrompts.jsx b/packages/ui/src/ui-component/extended/StarterPrompts.jsx index f19f326a..89a40642 100644 --- a/packages/ui/src/ui-component/extended/StarterPrompts.jsx +++ b/packages/ui/src/ui-component/extended/StarterPrompts.jsx @@ -81,7 +81,9 @@ const StarterPrompts = ({ dialogProps }) => { } } catch (error) { enqueueSnackbar({ - message: `Failed to save Conversation Starter Prompts: ${error.response.data.message}`, + message: `Failed to save Conversation Starter Prompts: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', diff --git a/packages/ui/src/views/apikey/APIKeyDialog.jsx b/packages/ui/src/views/apikey/APIKeyDialog.jsx index a59bb57f..6816a310 100644 --- a/packages/ui/src/views/apikey/APIKeyDialog.jsx +++ b/packages/ui/src/views/apikey/APIKeyDialog.jsx @@ -79,7 +79,9 @@ const APIKeyDialog = ({ show, dialogProps, onCancel, onConfirm, setError }) => { } catch (error) { setError(error) enqueueSnackbar({ - message: `Failed to add new API key: ${error.response.data.message}`, + message: `Failed to add new API key: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', @@ -116,7 +118,9 @@ const APIKeyDialog = ({ show, dialogProps, onCancel, onConfirm, setError }) => { } catch (error) { setError(error) enqueueSnackbar({ - message: `Failed to save API key: ${error.response.data.message}`, + message: `Failed to save API key: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', diff --git a/packages/ui/src/views/apikey/index.jsx b/packages/ui/src/views/apikey/index.jsx index 11d4e032..0ecc3a59 100644 --- a/packages/ui/src/views/apikey/index.jsx +++ b/packages/ui/src/views/apikey/index.jsx @@ -286,7 +286,9 @@ const APIKey = () => { } } catch (error) { enqueueSnackbar({ - message: `Failed to delete API key: ${error.response.data.message}`, + message: `Failed to delete API key: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', diff --git a/packages/ui/src/views/assistants/AssistantDialog.jsx b/packages/ui/src/views/assistants/AssistantDialog.jsx index 27f83732..802df39d 100644 --- a/packages/ui/src/views/assistants/AssistantDialog.jsx +++ b/packages/ui/src/views/assistants/AssistantDialog.jsx @@ -249,7 +249,9 @@ const AssistantDialog = ({ show, dialogProps, onCancel, onConfirm, setError }) = } catch (error) { setError(error) enqueueSnackbar({ - message: `Failed to add new Assistant: ${error.response.data.message}`, + message: `Failed to add new Assistant: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', @@ -303,7 +305,9 @@ const AssistantDialog = ({ show, dialogProps, onCancel, onConfirm, setError }) = } catch (error) { setError(error) enqueueSnackbar({ - message: `Failed to save Assistant: ${error.response.data.message}`, + message: `Failed to save Assistant: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', @@ -343,7 +347,9 @@ const AssistantDialog = ({ show, dialogProps, onCancel, onConfirm, setError }) = } catch (error) { setError(error) enqueueSnackbar({ - message: `Failed to sync Assistant: ${error.response.data.message}`, + message: `Failed to sync Assistant: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', @@ -390,7 +396,9 @@ const AssistantDialog = ({ show, dialogProps, onCancel, onConfirm, setError }) = } catch (error) { setError(error) enqueueSnackbar({ - message: `Failed to delete Assistant: ${error.response.data.message}`, + message: `Failed to delete Assistant: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', diff --git a/packages/ui/src/views/canvas/index.jsx b/packages/ui/src/views/canvas/index.jsx index 0e690218..c7a5ff01 100644 --- a/packages/ui/src/views/canvas/index.jsx +++ b/packages/ui/src/views/canvas/index.jsx @@ -173,7 +173,7 @@ const Canvas = () => { navigate('/') } catch (error) { enqueueSnackbar({ - message: error.response.data.message, + message: typeof error.response.data === 'object' ? error.response.data.message : error.response.data, options: { key: new Date().getTime() + Math.random(), variant: 'error', diff --git a/packages/ui/src/views/chatflows/ShareChatbot.jsx b/packages/ui/src/views/chatflows/ShareChatbot.jsx index 35003594..a9ecc71b 100644 --- a/packages/ui/src/views/chatflows/ShareChatbot.jsx +++ b/packages/ui/src/views/chatflows/ShareChatbot.jsx @@ -162,7 +162,9 @@ const ShareChatbot = ({ isSessionMemory }) => { } } catch (error) { enqueueSnackbar({ - message: `Failed to save Chatbot Configuration: ${error.response.data.message}`, + message: `Failed to save Chatbot Configuration: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', @@ -197,7 +199,9 @@ const ShareChatbot = ({ isSessionMemory }) => { } } catch (error) { enqueueSnackbar({ - message: `Failed to save Chatbot Configuration: ${error.response.data.message}`, + message: `Failed to save Chatbot Configuration: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', diff --git a/packages/ui/src/views/chatmessage/ChatMessage.jsx b/packages/ui/src/views/chatmessage/ChatMessage.jsx index 2b10455d..216e8869 100644 --- a/packages/ui/src/views/chatmessage/ChatMessage.jsx +++ b/packages/ui/src/views/chatmessage/ChatMessage.jsx @@ -406,10 +406,6 @@ export const ChatMessage = ({ open, chatflowid, isDialog, previews, setPreviews if (response.data) { const data = response.data - if (data.executionError) { - handleError(data.msg) - return - } setMessages((prevMessages) => { let allMessages = [...cloneDeep(prevMessages)] diff --git a/packages/ui/src/views/chatmessage/ChatPopUp.jsx b/packages/ui/src/views/chatmessage/ChatPopUp.jsx index b592643b..d54478db 100644 --- a/packages/ui/src/views/chatmessage/ChatPopUp.jsx +++ b/packages/ui/src/views/chatmessage/ChatPopUp.jsx @@ -106,7 +106,7 @@ export const ChatPopUp = ({ chatflowid }) => { }) } catch (error) { enqueueSnackbar({ - message: error.response.data.message, + message: typeof error.response.data === 'object' ? error.response.data.message : error.response.data, options: { key: new Date().getTime() + Math.random(), variant: 'error', diff --git a/packages/ui/src/views/credentials/AddEditCredentialDialog.jsx b/packages/ui/src/views/credentials/AddEditCredentialDialog.jsx index 7d36826f..dfdfe9af 100644 --- a/packages/ui/src/views/credentials/AddEditCredentialDialog.jsx +++ b/packages/ui/src/views/credentials/AddEditCredentialDialog.jsx @@ -134,7 +134,9 @@ const AddEditCredentialDialog = ({ show, dialogProps, onCancel, onConfirm, setEr } catch (error) { setError(error) enqueueSnackbar({ - message: `Failed to add new Credential: ${error.response.data.message}`, + message: `Failed to add new Credential: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', @@ -184,7 +186,9 @@ const AddEditCredentialDialog = ({ show, dialogProps, onCancel, onConfirm, setEr } catch (error) { setError(error) enqueueSnackbar({ - message: `Failed to save Credential: ${error.response.data.message}`, + message: `Failed to save Credential: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', diff --git a/packages/ui/src/views/credentials/index.jsx b/packages/ui/src/views/credentials/index.jsx index dbe07960..13413ec7 100644 --- a/packages/ui/src/views/credentials/index.jsx +++ b/packages/ui/src/views/credentials/index.jsx @@ -162,7 +162,9 @@ const Credentials = () => { } } catch (error) { enqueueSnackbar({ - message: `Failed to delete Credential: ${error.response.data.message}`, + message: `Failed to delete Credential: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', diff --git a/packages/ui/src/views/tools/ToolDialog.jsx b/packages/ui/src/views/tools/ToolDialog.jsx index a94ad494..43d53c32 100644 --- a/packages/ui/src/views/tools/ToolDialog.jsx +++ b/packages/ui/src/views/tools/ToolDialog.jsx @@ -233,7 +233,9 @@ const ToolDialog = ({ show, dialogProps, onUseTemplate, onCancel, onConfirm, set } } catch (error) { enqueueSnackbar({ - message: `Failed to export Tool: ${error.response.data.message}`, + message: `Failed to export Tool: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', @@ -277,7 +279,9 @@ const ToolDialog = ({ show, dialogProps, onUseTemplate, onCancel, onConfirm, set } } catch (error) { enqueueSnackbar({ - message: `Failed to add new Tool: ${error.response.data.message}`, + message: `Failed to add new Tool: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', @@ -319,7 +323,9 @@ const ToolDialog = ({ show, dialogProps, onUseTemplate, onCancel, onConfirm, set } } catch (error) { enqueueSnackbar({ - message: `Failed to save Tool: ${error.response.data.message}`, + message: `Failed to save Tool: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', @@ -364,7 +370,9 @@ const ToolDialog = ({ show, dialogProps, onUseTemplate, onCancel, onConfirm, set } } catch (error) { enqueueSnackbar({ - message: `Failed to delete Tool: ${error.response.data.message}`, + message: `Failed to delete Tool: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', diff --git a/packages/ui/src/views/variables/AddEditVariableDialog.jsx b/packages/ui/src/views/variables/AddEditVariableDialog.jsx index cf302497..c26c7d35 100644 --- a/packages/ui/src/views/variables/AddEditVariableDialog.jsx +++ b/packages/ui/src/views/variables/AddEditVariableDialog.jsx @@ -113,7 +113,9 @@ const AddEditVariableDialog = ({ show, dialogProps, onCancel, onConfirm, setErro } catch (err) { setError(err) enqueueSnackbar({ - message: `Failed to add new Variable: ${error.response.data.message}`, + message: `Failed to add new Variable: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', @@ -156,7 +158,9 @@ const AddEditVariableDialog = ({ show, dialogProps, onCancel, onConfirm, setErro } catch (error) { setError(err) enqueueSnackbar({ - message: `Failed to save Variable: ${error.response.data.message}`, + message: `Failed to save Variable: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', diff --git a/packages/ui/src/views/variables/index.jsx b/packages/ui/src/views/variables/index.jsx index 280711e9..c4436c94 100644 --- a/packages/ui/src/views/variables/index.jsx +++ b/packages/ui/src/views/variables/index.jsx @@ -149,7 +149,9 @@ const Variables = () => { } } catch (error) { enqueueSnackbar({ - message: `Failed to delete Variable: ${error.response.data.message}`, + message: `Failed to delete Variable: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', diff --git a/packages/ui/src/views/vectorstore/UpsertHistoryDialog.jsx b/packages/ui/src/views/vectorstore/UpsertHistoryDialog.jsx index 5c976ece..1d4b6aa2 100644 --- a/packages/ui/src/views/vectorstore/UpsertHistoryDialog.jsx +++ b/packages/ui/src/views/vectorstore/UpsertHistoryDialog.jsx @@ -259,7 +259,9 @@ const UpsertHistoryDialog = ({ show, dialogProps, onCancel }) => { setSelected([]) } catch (error) { enqueueSnackbar({ - message: 'Error deleting upsert history', + message: `Failed to delete Upsert History: ${ + typeof error.response.data === 'object' ? error.response.data.message : error.response.data + }`, options: { key: new Date().getTime() + Math.random(), variant: 'error', diff --git a/packages/ui/src/views/vectorstore/VectorStoreDialog.jsx b/packages/ui/src/views/vectorstore/VectorStoreDialog.jsx index 059f0c6e..18110c48 100644 --- a/packages/ui/src/views/vectorstore/VectorStoreDialog.jsx +++ b/packages/ui/src/views/vectorstore/VectorStoreDialog.jsx @@ -293,7 +293,7 @@ query(formData).then((response) => { if (res && res.data && typeof res.data === 'object') onIndexResult(res.data) } catch (error) { enqueueSnackbar({ - message: error.response.data.message, + message: typeof error.response.data === 'object' ? error.response.data.message : error.response.data, options: { key: new Date().getTime() + Math.random(), variant: 'error',