( error: Error | unknown, baseMessage: string, context?: Content[] | Record<string, unknown> | unknown[], type = 'general', reportingDir = os.tmpdir(), // for testing )
| 24 | * @param baseMessage The initial message to log to console.error before the report path. |
| 25 | */ |
| 26 | export async function reportError( |
| 27 | error: Error | unknown, |
| 28 | baseMessage: string, |
| 29 | context?: Content[] | Record<string, unknown> | unknown[], |
| 30 | type = 'general', |
| 31 | reportingDir = os.tmpdir(), // for testing |
| 32 | ): Promise<void> { |
| 33 | const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); |
| 34 | const reportFileName = `anus-client-error-${type}-${timestamp}.json`; |
| 35 | const reportPath = path.join(reportingDir, reportFileName); |
| 36 | |
| 37 | let errorToReport: { message: string; stack?: string }; |
| 38 | if (error instanceof Error) { |
| 39 | errorToReport = { message: error.message, stack: error.stack }; |
| 40 | } else if ( |
| 41 | typeof error === 'object' && |
| 42 | error !== null && |
| 43 | 'message' in error |
| 44 | ) { |
| 45 | errorToReport = { |
| 46 | message: String((error as { message: unknown }).message), |
| 47 | }; |
| 48 | } else { |
| 49 | errorToReport = { message: String(error) }; |
| 50 | } |
| 51 | |
| 52 | const reportContent: ErrorReportData = { error: errorToReport }; |
| 53 | |
| 54 | if (context) { |
| 55 | reportContent.context = context; |
| 56 | } |
| 57 | |
| 58 | let stringifiedReportContent: string; |
| 59 | try { |
| 60 | stringifiedReportContent = JSON.stringify(reportContent, null, 2); |
| 61 | } catch (stringifyError) { |
| 62 | // This can happen if context contains something like BigInt |
| 63 | console.error( |
| 64 | `${baseMessage} Could not stringify report content (likely due to context):`, |
| 65 | stringifyError, |
| 66 | ); |
| 67 | console.error('Original error that triggered report generation:', error); |
| 68 | if (context) { |
| 69 | console.error( |
| 70 | 'Original context could not be stringified or included in report.', |
| 71 | ); |
| 72 | } |
| 73 | // Fallback: try to report only the error if context was the issue |
| 74 | try { |
| 75 | const minimalReportContent = { error: errorToReport }; |
| 76 | stringifiedReportContent = JSON.stringify(minimalReportContent, null, 2); |
| 77 | // Still try to write the minimal report |
| 78 | await fs.writeFile(reportPath, stringifiedReportContent); |
| 79 | console.error( |
| 80 | `${baseMessage} Partial report (excluding context) available at: ${reportPath}`, |
| 81 | ); |
| 82 | } catch (minimalWriteError) { |
| 83 | console.error( |
no outgoing calls
no test coverage detected