From 1144c4582613ff0001ffb0b9916c0906dc3c0f78 Mon Sep 17 00:00:00 2001 From: OlgunR Date: Fri, 29 May 2026 09:20:34 +0200 Subject: [PATCH] Improve error handling in PDF processing workflow Refactored the PDF processing workflow to enhance error handling and provide more descriptive exception messages. Added `try-catch` blocks around the PDF/A-3b conversion and document saving steps to handle potential failures. Labeled the workflow steps for clarity: - Step 1: Convert to PDF/A-3b - Step 2: Buffer converted PDF - Step 3: Embed attachment - Step 4: Save document Removed redundant `MemoryStream` initialization for the original PDF and updated comments to improve code readability and maintainability. --- .../Services/PdfResultPackageService.cs | 35 ++++++++++++++----- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/DXApp.TemplateKitProject/Services/PdfResultPackageService.cs b/DXApp.TemplateKitProject/Services/PdfResultPackageService.cs index c9b0898..e8990ce 100644 --- a/DXApp.TemplateKitProject/Services/PdfResultPackageService.cs +++ b/DXApp.TemplateKitProject/Services/PdfResultPackageService.cs @@ -35,20 +35,28 @@ public class PdfResultPackageService( // 3. Original auf PDF/A-3b hochstufen + Bericht anhängen await Task.Run(() => { - // Original in MemoryStream laden using var inputStream = new MemoryStream(originalPdfBytes); - using var outputStream = new MemoryStream(); - // PDF/A-3b Konvertierung - var converter = new PdfDocumentConverter(inputStream); - converter.Convert(PdfCompatibility.PdfA3b); + // Schritt 1: PDF/A-3b Konvertierung + PdfDocumentConverter converter; + try + { + converter = new PdfDocumentConverter(inputStream); + converter.Convert(PdfCompatibility.PdfA3b); + } + catch (Exception ex) + { + throw new InvalidOperationException( + "Konvertierung nach PDF/A-3b fehlgeschlagen. " + + "Die Originaldatei ist möglicherweise beschädigt oder nicht konvertierbar.", ex); + } - // Konvertiertes PDF in MemoryStream speichern + // Schritt 2: Konvertiertes PDF puffern using var convertedStream = new MemoryStream(); converter.SaveDocument(convertedStream); convertedStream.Position = 0; - // Bericht als Anhang einbetten + // Schritt 3: Anhang einbetten using var processor = new PdfDocumentProcessor(); processor.LoadDocument(convertedStream); @@ -62,8 +70,17 @@ public class PdfResultPackageService( Data = File.ReadAllBytes(reportPath) }); - // Speichern - processor.SaveDocument(outputPath); + // Schritt 4: Speichern + try + { + processor.SaveDocument(outputPath); + } + catch (Exception ex) + { + throw new InvalidOperationException( + $"Result-PDF konnte nicht gespeichert werden unter '{outputPath}'. " + + "Prüfe ob das Verzeichnis existiert und beschreibbar ist.", ex); + } }); logger.LogInformation(