diff --git a/src/lib/misc/ErrorHandler.tsx b/src/lib/misc/ErrorHandler.tsx index a1451ecf3..ea860fb46 100644 --- a/src/lib/misc/ErrorHandler.tsx +++ b/src/lib/misc/ErrorHandler.tsx @@ -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( @@ -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); } diff --git a/src/server.ts b/src/server.ts index 0bea9803c..d80c96d31 100644 --- a/src/server.ts +++ b/src/server.ts @@ -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); } } ); diff --git a/src/services/UploadService.ts b/src/services/UploadService.ts index 99b2313e7..091954a51 100644 --- a/src/services/UploadService.ts +++ b/src/services/UploadService.ts @@ -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); } } }