From 7390cbdbbbece823b6af0f46ce54555d1a6aab7c Mon Sep 17 00:00:00 2001 From: Matias Espinoza Date: Mon, 13 Mar 2023 13:23:11 -0300 Subject: [PATCH] Improved support for error handling --- src/api/index.ts | 13 +++++++++---- src/bot/index.ts | 6 ++++-- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/api/index.ts b/src/api/index.ts index 751b2a3..b6651da 100644 --- a/src/api/index.ts +++ b/src/api/index.ts @@ -1,6 +1,7 @@ import { ChatCompletionRequestMessage, ChatCompletionResponseMessage, Configuration, OpenAIApi, } from 'openai'; +import process from 'process'; import { AI } from '@/models/ai'; import { Runnable } from '@/models/runnable'; import { Logger } from '@/logger'; @@ -8,7 +9,7 @@ import { Logger } from '@/logger'; export class Api implements AI, Runnable { private _logger: Logger; - private _api: OpenAIApi; + private _api!: OpenAIApi; private readonly _configuration: Configuration; @@ -18,12 +19,16 @@ export class Api implements AI, Runnable { this._configuration = new Configuration({ apiKey: process.env.OPENAI_API_KEY, }); - - this._api = new OpenAIApi(this._configuration); } run(): void { - this._logger.service.info('OpenAI Service has been initialized successfully.'); + try { + this._api = new OpenAIApi(this._configuration); + this._logger.service.info('OpenAI Service has been initialized successfully.'); + } catch (error) { + this._logger.service.error(`Failed to start OpenAI Service: ${error}`); + process.exit(1); + } } async chatCompletion(chatHistory: ChatCompletionRequestMessage[]) diff --git a/src/bot/index.ts b/src/bot/index.ts index 6710af3..f48705c 100644 --- a/src/bot/index.ts +++ b/src/bot/index.ts @@ -1,6 +1,7 @@ import { ActivityType, Client, CommandInteraction, IntentsBitField, Interaction, Partials, } from 'discord.js'; +import process from 'process'; import { Logger } from '@/logger'; import { Runnable } from '@/models/runnable'; import { AI } from '@/models/ai'; @@ -46,8 +47,9 @@ export class Bot implements Runnable { run(): void { this._client.login(process.env.DISCORD_API_KEY).then(() => { this._logger.service.info('Discord Service has been initialized successfully.'); - }).catch((reason) => { - this._logger.service.error(`Failed to start Discord Service: ${reason}`); + }).catch((error) => { + this._logger.service.error(`Failed to start Discord Service: ${error}`); + process.exit(1); }); this._client.on('ready', async () => {