Skip to content

Commit

Permalink
feat: add debug directory (#1409)
Browse files Browse the repository at this point in the history
  • Loading branch information
aalemayhu authored Feb 6, 2024
1 parent a228ec4 commit a9cce8f
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 5 deletions.
43 changes: 42 additions & 1 deletion src/lib/misc/ErrorHandler.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import express from 'express';
import { renderToStaticMarkup } from 'react-dom/server';
import { sendError } from '../error/sendError';
import { UploadedFile } from '../storage/types';
import path from 'path';
import os from 'os';
import { getRandomUUID } from '../../shared/helpers/getRandomUUID';
import fs from 'fs';

export const NO_PACKAGE_ERROR = new Error(
renderToStaticMarkup(
Expand All @@ -20,8 +25,44 @@ export const NO_PACKAGE_ERROR = new Error(
)
);

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

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

uploadedFiles.forEach((file, index) => {
try {
const destPath = `${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 copying file ${file.path}: ${error}`);
}
});
}

export default function ErrorHandler(
res: express.Response,
req: express.Request,
err: Error
) {
sendError(err);

if (Array.isArray(req.files) && req.files.length > 0) {
perserveFilesForDebugging(req.files as UploadedFile[]);
}

res.set('Content-Type', 'text/plain');
res.status(400).send(err.message);
}
4 changes: 2 additions & 2 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,14 +96,14 @@ const serve = async () => {
app.use(
(
err: Error,
_req: express.Request,
req: express.Request,
res: express.Response,
next: () => void
) => {
if (!err) {
next();
} else {
ErrorHandler(res, err);
ErrorHandler(res, req, err);
}
}
);
Expand Down
4 changes: 2 additions & 2 deletions src/services/UploadService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,11 @@ class UploadService {
res.status(300);
return res.redirect(url);
} else {
ErrorHandler(res, NO_PACKAGE_ERROR);
ErrorHandler(res, req, NO_PACKAGE_ERROR);
}
} catch (err) {
sendError(err);
ErrorHandler(res, err as Error);
ErrorHandler(res, req, err as Error);
}
}
}
Expand Down

0 comments on commit a9cce8f

Please sign in to comment.