Centralizes export error handling

Introduces `ExportErrorHandler` to manage export-related errors, progress notices, and batch results.

This change provides a unified way to handle errors, display progress, and report results of export operations, improving code maintainability and user experience.
This commit is contained in:
AlexKucera committed 2025-09-03 19:43:52 +02:00
1 parent 608a51b81e
commit f9a6166da3
2 files changed
+201 -52

No files matched your search

+30 -52
View File
@@ -23,6 +23,7 @@ import { obsidianTypstPDFExportSettings, DEFAULT_SETTINGS, ExportFormat } from '
import { FALLBACK_FONTS, PLUGIN_DIRS } from './src/core/constants';
import { DependencyChecker } from './src/core/DependencyChecker';
import { ModalSettingsHelper } from './src/core/ModalSettingsHelper';
import { ExportErrorHandler } from './src/core/ExportErrorHandler';
import { PandocTypstConverter } from './src/converters/PandocTypstConverter';
import { ExportConfigModal } from './src/modal/ExportConfigModal';
import { ExportConfig, ExportConfigModalSettings } from './src/modal/types';
@@ -399,32 +400,21 @@ export class obsidianTypstPDFExport extends Plugin {
return;
}
new Notice(`Exporting ${files.length} files to PDF...`);
ExportErrorHandler.showProgressNotice(`Exporting ${files.length} files to PDF...`);
let successful = 0;
let failed = 0;
const errors: string[] = [];
const { recordSuccess, recordError, getResult } = ExportErrorHandler.createBatchTracker();
for (const file of files) {
try {
await this.exportFile(file);
successful++;
recordSuccess();
} catch (error) {
console.error(`Failed to export ${file.name}:`, error);
failed++;
errors.push(`${file.name}: ${error.message || error}`);
recordError(file.name, error);
}
}
// Show completion notice
if (failed === 0) {
new Notice(`✓ Successfully exported ${successful} files`);
} else {
new Notice(`Export complete: ${successful} successful, ${failed} failed`, 5000);
if (errors.length > 0) {
console.error('Export errors:', errors);
}
}
// Show final result
ExportErrorHandler.handleBatchResult(getResult());
}
/**
@@ -439,7 +429,7 @@ export class obsidianTypstPDFExport extends Plugin {
this.currentExportController = new AbortController();
// Show progress notice
const progressNotice = new Notice('Exporting to PDF...', 0);
const progressNotice = ExportErrorHandler.showProgressNotice('Exporting to PDF...');
// Read file content
const content = await this.app.vault.read(file);
@@ -534,8 +524,7 @@ export class obsidianTypstPDFExport extends Plugin {
new Notice(`Export failed: ${result.error}`);
}
} catch (error) {
console.error('Export error:', error);
new Notice(`Export failed: ${error.message}`);
ExportErrorHandler.handleSingleExportError(error);
} finally {
this.currentExportController = null;
@@ -578,32 +567,21 @@ export class obsidianTypstPDFExport extends Plugin {
return;
}
new Notice(`Exporting ${files.length} files with custom configuration...`);
ExportErrorHandler.showProgressNotice(`Exporting ${files.length} files with custom configuration...`);
let successful = 0;
let failed = 0;
const errors: string[] = [];
const { recordSuccess, recordError, getResult } = ExportErrorHandler.createBatchTracker();
for (const file of files) {
try {
await this.exportFileWithConfig(file, config);
successful++;
recordSuccess();
} catch (error) {
console.error(`Failed to export ${file.name}:`, error);
failed++;
errors.push(`${file.name}: ${error.message || error}`);
recordError(file.name, error);
}
}
// Show completion notice
if (failed === 0) {
new Notice(`✓ Successfully exported ${successful} files`);
} else {
new Notice(`Export complete: ${successful} successful, ${failed} failed`, 5000);
if (errors.length > 0) {
console.error('Export errors:', errors);
}
}
// Show final result
ExportErrorHandler.handleBatchResult(getResult());
}
/**
@@ -613,7 +591,7 @@ export class obsidianTypstPDFExport extends Plugin {
if (this.currentExportController) {
this.currentExportController.abort();
this.currentExportController = null;
new Notice('Export cancelled');
ExportErrorHandler.showCancellationNotice();
}
}
@@ -632,24 +610,20 @@ export class obsidianTypstPDFExport extends Plugin {
return;
}
new Notice(`Exporting ${markdownFiles.length} files from ${folder.name}...`);
ExportErrorHandler.showProgressNotice(`Exporting ${markdownFiles.length} files from ${folder.name}...`);
let successful = 0;
let failed = 0;
const { recordSuccess, recordError, getResult } = ExportErrorHandler.createBatchTracker();
for (const file of markdownFiles) {
try {
await this.exportFile(file);
successful++;
recordSuccess();
} catch (error) {
console.error(`Failed to export ${file.name}:`, error);
failed++;
recordError(file.name, error);
}
}
new Notice(
`Export complete: ${successful} successful, ${failed} failed`
);
ExportErrorHandler.handleBatchResult(getResult());
}
/**
@@ -694,7 +668,7 @@ ${dependencyResult.allAvailable
);
}
} catch (error) {
console.error('Error checking dependencies:', error);
ExportErrorHandler.handleDependencyError('Dependencies', error, false);
}
}
@@ -803,7 +777,7 @@ ${dependencyResult.allAvailable
updatedContent = updatedContent.replace(pdfEmbed.marker, fallbackOutput);
}
} catch (error) {
console.error(`Export: Error processing PDF embed ${pdfEmbed.originalPath}:`, error);
ExportErrorHandler.handleProcessingError('PDF embed', pdfEmbed.originalPath, error);
// Still try to embed the PDF even if there's a processing error
const relativePdfPath = pathModule.relative(vaultBasePath, pdfEmbed.originalPath);
const fallbackOutput = [
@@ -880,9 +854,13 @@ ${dependencyResult.allAvailable
console.log(`Export: Successfully processed image embed: ${imageEmbed.originalPath}`);
} catch (error) {
console.error(`Export: Error processing image embed ${imageEmbed.originalPath}:`, error);
const fallbackOutput = `[⚠️ **Image processing error:** ${imageEmbed.alt || imageEmbed.originalPath}]`;
updatedContent = updatedContent.replace(imageEmbed.marker, fallbackOutput);
const { fallback } = ExportErrorHandler.handleProcessingError(
'image embed',
imageEmbed.originalPath,
error,
`[⚠️ **Image processing error:** ${imageEmbed.alt || imageEmbed.originalPath}]`
);
updatedContent = updatedContent.replace(imageEmbed.marker, fallback);
}
}
+171
View File
@@ -0,0 +1,171 @@
/**
* Centralized error handling utilities for export operations
*/
import { Notice } from 'obsidian';
import { EXPORT_CONSTANTS } from './constants';
export interface BatchExportResult {
successful: number;
failed: number;
errors: string[];
}
export interface ExportError {
fileName?: string;
operation: string;
error: Error | string;
shouldShowNotice?: boolean;
logLevel?: 'error' | 'warn' | 'info';
}
export class ExportErrorHandler {
/**
* Handle batch export results with consistent messaging
*/
public static handleBatchResult(
result: BatchExportResult,
operationDescription: string = 'Export'
): void {
const { successful, failed, errors } = result;
if (failed === 0) {
new Notice(`✓ Successfully exported ${successful} files`);
} else {
new Notice(
`${operationDescription} complete: ${successful} successful, ${failed} failed`,
EXPORT_CONSTANTS.NOTICE_DURATION.SHORT
);
if (errors.length > 0) {
console.error(`${operationDescription} errors:`, errors);
}
}
}
/**
* Handle individual export errors consistently
*/
public static handleExportError(exportError: ExportError): string {
const { fileName, operation, error, shouldShowNotice = false, logLevel = 'error' } = exportError;
const errorMessage = error instanceof Error ? error.message : String(error);
const fullMessage = fileName ? `${fileName}: ${errorMessage}` : errorMessage;
// Log the error
switch (logLevel) {
case 'error':
console.error(`${operation}:`, error);
break;
case 'warn':
console.warn(`${operation}:`, error);
break;
case 'info':
console.info(`${operation}:`, error);
break;
}
// Show notice if requested
if (shouldShowNotice) {
new Notice(`${operation} failed: ${errorMessage}`);
}
return fullMessage;
}
/**
* Handle processing errors for embeds and similar operations
*/
public static handleProcessingError(
operation: string,
itemPath: string,
error: Error | string,
fallbackContent?: string
): { errorMessage: string; fallback: string } {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error(`Export: Error processing ${operation} ${itemPath}:`, error);
const fallback = fallbackContent ||
`[⚠️ **${operation} processing error:** ${itemPath}]`;
return {
errorMessage: `${operation} processing failed: ${errorMessage}`,
fallback
};
}
/**
* Create a batch export tracker for consistent error collection
*/
public static createBatchTracker(): {
tracker: BatchExportResult;
recordSuccess: () => void;
recordError: (fileName: string, error: Error | string) => void;
getResult: () => BatchExportResult;
} {
const tracker: BatchExportResult = {
successful: 0,
failed: 0,
errors: []
};
return {
tracker,
recordSuccess: () => {
tracker.successful++;
},
recordError: (fileName: string, error: Error | string) => {
tracker.failed++;
const errorMessage = error instanceof Error ? error.message : String(error);
tracker.errors.push(`${fileName}: ${errorMessage}`);
// Also log individual errors
console.error(`Failed to export ${fileName}:`, error);
},
getResult: () => tracker
};
}
/**
* Handle single file export errors with proper notices
*/
public static handleSingleExportError(error: Error | string): void {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error('Export error:', error);
new Notice(`Export failed: ${errorMessage}`);
}
/**
* Handle dependency or configuration errors
*/
public static handleDependencyError(
dependency: string,
error: Error | string,
showNotice: boolean = true
): void {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error(`Error checking ${dependency}:`, error);
if (showNotice) {
new Notice(
`${dependency} error: ${errorMessage}`,
EXPORT_CONSTANTS.NOTICE_DURATION.LONG
);
}
}
/**
* Show export progress notice
*/
public static showProgressNotice(message: string, timeout?: number): Notice {
return new Notice(message, timeout || 0);
}
/**
* Show export cancellation notice
*/
public static showCancellationNotice(): void {
new Notice('Export cancelled');
}
}