Skip to content

Commit

Permalink
refactor: move error handling code to error and debug
Browse files Browse the repository at this point in the history
  • Loading branch information
aalemayhu committed Dec 15, 2024
1 parent 08df16f commit 836ce59
Show file tree
Hide file tree
Showing 7 changed files with 84 additions and 80 deletions.
36 changes: 36 additions & 0 deletions src/lib/debug/perserveFilesForDebugging.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import path from 'path';
import fs from 'fs';
import os from 'os';

import { getRandomUUID } from '../../shared/helpers/getRandomUUID';
import { UploadedFile } from '../storage/types';

export function perserveFilesForDebugging(
uploadedFiles: UploadedFile[],
err: Error
) {
const debugDirectory = path.join(os.tmpdir(), 'debug', getRandomUUID());

try {
if (!fs.existsSync(debugDirectory)) {
fs.mkdirSync(debugDirectory, { recursive: true });
console.log(`Created debug directory: ${debugDirectory}`);
}

const timestamp = new Date().toISOString();
const errorMessage = `${timestamp} - ${err.name}: \n${err.message}\n${err.stack}`;
fs.writeFileSync(`${debugDirectory}/error.txt`, errorMessage);

uploadedFiles.forEach((file, index) => {
const destPath = path.join(
debugDirectory,
`${index}-${path.basename(file.originalname)}`
);
const fileContents = fs.readFileSync(file.path);
fs.writeFileSync(destPath, fileContents);
console.log(`Copied file ${file.path} to ${destPath}`);
});
} catch (error) {
console.error(`Error in perserveFilesForDebugging: ${error}`);
}
}
19 changes: 19 additions & 0 deletions src/lib/error/constants.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { renderToStaticMarkup } from 'react-dom/server';

export const NO_PACKAGE_ERROR = new Error(
renderToStaticMarkup(
<>
<div className="info">
Could not create a deck using your file(s) and rules. Make sure to at
least create on valid toggle or verify your{' '}
<a href="/upload?view=template">settings</a>? Example:
</div>
<div className="card" style={{ width: '50%', padding: '1rem' }}>
<details>
<summary>This the front</summary>
This is the back
</details>
</div>
</>
)
);
77 changes: 0 additions & 77 deletions src/lib/misc/ErrorHandler.tsx

This file was deleted.

2 changes: 1 addition & 1 deletion src/lib/parser/DeckParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import replaceAll from './helpers/replaceAll';
import get16DigitRandomId from '../../shared/helpers/get16DigitRandomId';
import { isValidAudioFile } from '../anki/format';
import { sendError } from '../error/sendError';
import { NO_PACKAGE_ERROR } from '../misc/ErrorHandler';
import FallbackParser from './experimental/FallbackParser';
import { embedFile } from './exporters/embedFile';
import getYouTubeEmbedLink from './helpers/getYouTubeEmbedLink';
Expand All @@ -28,6 +27,7 @@ import { extractStyles } from './extractStyles';
import { withFontSize } from './withFontSize';
import { transformDetailsTagToNotionToggleList } from './transformDetailsTagToNotionToggleList';
import { findNotionToggleLists } from './findNotionToggleLists';
import { NO_PACKAGE_ERROR } from '../error/constants';

export interface DeckParserInput {
name: string;
Expand Down
25 changes: 25 additions & 0 deletions src/routes/middleware/ErrorHandler.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import express from 'express';
import { sendError } from '../../lib/error/sendError';
import { UploadedFile } from '../../lib/storage/types';
import { isLimitError } from '../../lib/misc/isLimitError';
import { isEmptyPayload } from '../../lib/misc/isEmptyPayload';
import { perserveFilesForDebugging } from '../../lib/debug/perserveFilesForDebugging';

export default function ErrorHandler(
res: express.Response,
req: express.Request,
err: Error
) {
const uploadedFiles = req.files as UploadedFile[];
const skipError = isLimitError(err);

if (!skipError) {
sendError(err);
if (!isEmptyPayload(uploadedFiles)) {
perserveFilesForDebugging(req.files as UploadedFile[], err);
}
}

res.set('Content-Type', 'text/plain');
res.status(400).send(err.message);
}
2 changes: 1 addition & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ if (existsSync(localEnvFile)) {
}

import { ALLOWED_ORIGINS, BUILD_DIR } from './lib/constants';
import ErrorHandler from './lib/misc/ErrorHandler';
import ErrorHandler from './routes/middleware/ErrorHandler';

// Server Endpoints
import settingsRouter from './routes/SettingsRouter';
Expand Down
3 changes: 2 additions & 1 deletion src/services/UploadService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import express from 'express';

import { IUploadRepository } from '../data_layer/UploadRespository';
import { sendError } from '../lib/error/sendError';
import ErrorHandler, { NO_PACKAGE_ERROR } from '../lib/misc/ErrorHandler';
import ErrorHandler from '../routes/middleware/ErrorHandler';
import Settings from '../lib/parser/Settings';
import Workspace from '../lib/parser/WorkSpace';
import StorageHandler from '../lib/storage/StorageHandler';
Expand All @@ -12,6 +12,7 @@ import { toText } from './NotionService/BlockHandler/helpers/deckNameToText';
import { isPaying } from '../lib/isPaying';
import { isLimitError } from '../lib/misc/isLimitError';
import { handleUploadLimitError } from '../controllers/Upload/helpers/handleUploadLimitError';
import { NO_PACKAGE_ERROR } from '../lib/error/constants';

class UploadService {
getUploadsByOwner(owner: number) {
Expand Down

0 comments on commit 836ce59

Please sign in to comment.