11import express from 'express' ;
22import { renderToStaticMarkup } from 'react-dom/server' ;
33import { sendError } from '../error/sendError' ;
4+ import { UploadedFile } from '../storage/types' ;
5+ import path from 'path' ;
6+ import os from 'os' ;
7+ import { getRandomUUID } from '../../shared/helpers/getRandomUUID' ;
8+ import fs from 'fs' ;
49
510export const NO_PACKAGE_ERROR = new Error (
611 renderToStaticMarkup (
@@ -20,8 +25,44 @@ export const NO_PACKAGE_ERROR = new Error(
2025 )
2126) ;
2227
23- export default function ErrorHandler ( res : express . Response , err : Error ) {
28+ function perserveFilesForDebugging ( uploadedFiles : UploadedFile [ ] ) {
29+ const debugDirectory = path . join ( os . tmpdir ( ) , 'debug' , getRandomUUID ( ) ) ;
30+
31+ if ( ! fs . existsSync ( debugDirectory ) ) {
32+ try {
33+ fs . mkdirSync ( debugDirectory , { recursive : true } ) ;
34+ console . log ( `Created debug directory: ${ debugDirectory } ` ) ;
35+ } catch ( error ) {
36+ console . error ( `Failed to create debug directory: ${ error } ` ) ;
37+ return ;
38+ }
39+ }
40+
41+ uploadedFiles . forEach ( ( file , index ) => {
42+ try {
43+ const destPath = `${ debugDirectory } /${ index } -${ path . basename (
44+ file . originalname
45+ ) } `;
46+ const fileContents = fs . readFileSync ( file . path ) ;
47+ fs . writeFileSync ( destPath , fileContents ) ;
48+ console . log ( `Copied file ${ file . path } to ${ destPath } ` ) ;
49+ } catch ( error ) {
50+ console . error ( `Error copying file ${ file . path } : ${ error } ` ) ;
51+ }
52+ } ) ;
53+ }
54+
55+ export default function ErrorHandler (
56+ res : express . Response ,
57+ req : express . Request ,
58+ err : Error
59+ ) {
2460 sendError ( err ) ;
61+
62+ if ( Array . isArray ( req . files ) && req . files . length > 0 ) {
63+ perserveFilesForDebugging ( req . files as UploadedFile [ ] ) ;
64+ }
65+
2566 res . set ( 'Content-Type' , 'text/plain' ) ;
2667 res . status ( 400 ) . send ( err . message ) ;
2768}
0 commit comments