From 5cdb83601db38e8844101867a57c9262f954a225 Mon Sep 17 00:00:00 2001 From: Lorenz Stechauner Date: Wed, 2 Dec 2026 14:40:29 +0100 Subject: [PATCH] Elwig: Update Exception usage patterns --- Elwig/Documents/CreditNote.cs | 2 +- Elwig/Documents/DeliveryConfirmation.cs | 4 ++-- Elwig/Documents/MemberDataSheet.cs | 2 +- Elwig/Documents/PaymentVariantSummary.cs | 2 +- Elwig/Helpers/AppDbUpdater.cs | 4 ++-- Elwig/Helpers/Billing/BillingVariant.cs | 2 +- Elwig/Helpers/Exceptions.cs | 9 +++++++++ Elwig/Helpers/Export/Ebics.cs | 2 +- Elwig/Helpers/Extensions.cs | 8 ++++---- Elwig/Helpers/Printing/PdfPrinter.cs | 2 +- Elwig/Helpers/Weighing/WeighingException.cs | 6 ------ Elwig/Services/InteractionService.cs | 17 +++++++++++++--- Elwig/Services/OrganicService.cs | 20 +++++++++---------- Tests/UnitTests/ExportTests/ElwigDataTest.cs | 4 ++-- .../ScaleTestGrInzersdorfL246.cs | 1 + .../WeighingTests/ScaleTestHaugsdorfDMA02.cs | 1 + .../WeighingTests/ScaleTestMatzenIT3000A.cs | 1 + .../ScaleTestSitzendorfDMA03Baby.cs | 1 + .../ScaleTestWolkersdorfIT6000E.cs | 1 + 19 files changed, 54 insertions(+), 35 deletions(-) create mode 100644 Elwig/Helpers/Exceptions.cs delete mode 100644 Elwig/Helpers/Weighing/WeighingException.cs diff --git a/Elwig/Documents/CreditNote.cs b/Elwig/Documents/CreditNote.cs index f1abcea..9f66e51 100644 --- a/Elwig/Documents/CreditNote.cs +++ b/Elwig/Documents/CreditNote.cs @@ -132,7 +132,7 @@ namespace Elwig.Documents { } protected override void RenderBody(iText.Layout.Document doc, PdfDocument pdf) { - if (_data == null) throw new Exception("Call LoadData before RenderBody"); + if (_data == null) throw new InvalidOperationException("Call LoadData before RenderBody"); base.RenderBody(doc, pdf); doc.Add(NewCreditTable(_data)); diff --git a/Elwig/Documents/DeliveryConfirmation.cs b/Elwig/Documents/DeliveryConfirmation.cs index 95e4f9e..437dc37 100644 --- a/Elwig/Documents/DeliveryConfirmation.cs +++ b/Elwig/Documents/DeliveryConfirmation.cs @@ -51,7 +51,7 @@ namespace Elwig.Documents { } protected override void BeforeRenderBody(iText.Layout.Document doc, PdfDocument pdf) { - if (Data == null) throw new Exception("Call LoadData before BeforeRenderBody"); + if (Data == null) throw new InvalidOperationException("Call LoadData before BeforeRenderBody"); base.BeforeRenderBody(doc, pdf); var firstDay = Data.Rows.MinBy(r => r.Date)?.Date; var lastDay = Data.Rows.MaxBy(r => r.Date)?.Date; @@ -62,7 +62,7 @@ namespace Elwig.Documents { } protected override void RenderBody(iText.Layout.Document doc, PdfDocument pdf) { - if (Season == null || Data == null) throw new Exception("Call LoadData before RenderBody"); + if (Season == null || Data == null) throw new InvalidOperationException("Call LoadData before RenderBody"); base.RenderBody(doc, pdf); doc.Add(NewDeliveryListTable(Data)); diff --git a/Elwig/Documents/MemberDataSheet.cs b/Elwig/Documents/MemberDataSheet.cs index fb5c78c..33c22a6 100644 --- a/Elwig/Documents/MemberDataSheet.cs +++ b/Elwig/Documents/MemberDataSheet.cs @@ -57,7 +57,7 @@ namespace Elwig.Documents { } protected override void RenderBody(iText.Layout.Document doc, PdfDocument pdf) { - if (Season == null) throw new Exception("Call LoadData before RenderBody"); + if (Season == null) throw new InvalidOperationException("Call LoadData before RenderBody"); base.RenderBody(doc, pdf); doc.Add(NewMemberData(Season).SetMarginBottomMM(5)); doc.Add(NewBucketTable(Season, MemberBuckets, MemberDeliveredWeightRed, MemberDeliveredWeightWhite, includeDelivery: false)); diff --git a/Elwig/Documents/PaymentVariantSummary.cs b/Elwig/Documents/PaymentVariantSummary.cs index 3b87e41..1e5d5bd 100644 --- a/Elwig/Documents/PaymentVariantSummary.cs +++ b/Elwig/Documents/PaymentVariantSummary.cs @@ -60,7 +60,7 @@ namespace Elwig.Documents { } protected override void RenderBody(iText.Layout.Document doc, PdfDocument pdf) { - if (Data == null || Modifiers == null || ModifierStat == null) throw new Exception("Call LoadData before RenderBody"); + if (Data == null || Modifiers == null || ModifierStat == null) throw new InvalidOperationException("Call LoadData before RenderBody"); base.RenderBody(doc, pdf); doc.Add(new KernedParagraph($"{Name} Lese {Variant.Year}", 24) .SetTextAlignment(TextAlignment.CENTER).SetFont(BF) diff --git a/Elwig/Helpers/AppDbUpdater.cs b/Elwig/Helpers/AppDbUpdater.cs index 255cdc5..e556742 100644 --- a/Elwig/Helpers/AppDbUpdater.cs +++ b/Elwig/Helpers/AppDbUpdater.cs @@ -57,9 +57,9 @@ namespace Elwig.Helpers { if (fromVersion == toVersion) { return; } else if (fromVersion > toVersion) { - throw new Exception("schema_version of database is too new"); + throw new DatabaseVersionTooNewException("schema_version of database is too new"); } else if (fromVersion <= 0) { - throw new Exception("schema_version of database is invalid"); + throw new DatabaseIntegrityException("schema_version of database is invalid"); } var asm = Assembly.GetExecutingAssembly(); diff --git a/Elwig/Helpers/Billing/BillingVariant.cs b/Elwig/Helpers/Billing/BillingVariant.cs index 188471a..89f0b8e 100644 --- a/Elwig/Helpers/Billing/BillingVariant.cs +++ b/Elwig/Helpers/Billing/BillingVariant.cs @@ -38,7 +38,7 @@ namespace Elwig.Helpers.Billing { } public async Task Calculate(bool strictPrices = true, bool? honorContracted = null, bool? allowAttrsIntoLower = null, bool? avoidUnderDeliveries = null) { - if (PaymentVariant == null || Data == null) throw new Exception("Call Load before Calculate"); + if (PaymentVariant == null || Data == null) throw new InvalidOperationException("Call Load before Calculate"); using var cnx = await AppDbContext.ConnectAsync(); using var tx = await cnx.BeginTransactionAsync(); await CalculateBuckets(honorContracted, allowAttrsIntoLower, avoidUnderDeliveries, cnx); diff --git a/Elwig/Helpers/Exceptions.cs b/Elwig/Helpers/Exceptions.cs new file mode 100644 index 0000000..c5c8ae2 --- /dev/null +++ b/Elwig/Helpers/Exceptions.cs @@ -0,0 +1,9 @@ +using System; +using System.IO; + +namespace Elwig.Helpers { + public class DatabaseIntegrityException(string? message = null) : SystemException(message) { } + public class DatabaseForeignKeyViolationException(string? message = null) : DatabaseIntegrityException(message) { } + public class DatabaseVersionTooNewException(string? message = null) : DatabaseIntegrityException(message) { } + public class WeighingException(string? message = null) : ApplicationException(message) { } +} diff --git a/Elwig/Helpers/Export/Ebics.cs b/Elwig/Helpers/Export/Ebics.cs index e17ab6a..af7ebe6 100644 --- a/Elwig/Helpers/Export/Ebics.cs +++ b/Elwig/Helpers/Export/Ebics.cs @@ -32,7 +32,7 @@ namespace Elwig.Helpers.Export { if (transactions.Any(tx => tx.Amount < 0)) { throw new ArgumentException("Tranaction amount may not be negative"); } else if (App.Client.Iban == null) { - throw new ArgumentException("Client IBAN has to be set"); + throw new ApplicationException("Mandanten-IBAN muss gesetzt sein"); } progress?.Report(0.0); var nbOfTxs = transactions.Count(); diff --git a/Elwig/Helpers/Extensions.cs b/Elwig/Helpers/Extensions.cs index 49e30db..dad5aaf 100644 --- a/Elwig/Helpers/Extensions.cs +++ b/Elwig/Helpers/Extensions.cs @@ -113,7 +113,7 @@ namespace Elwig.Helpers { return pwd; } catch { } } - throw new InvalidDataException("No matching password found"); + throw new ApplicationException("Kein passendes Passwort gefunden"); } public static async Task> CheckIntegrity(this ZipArchive zip, IEnumerable> passwords) { @@ -162,7 +162,7 @@ namespace Elwig.Helpers { } if (list.Count != 1 || list[0] != "ok") { - throw new FileFormatException($"Integrity problems ({list.Count}):\n" + string.Join("\n", list.Take(50))); + throw new DatabaseIntegrityException($"Integrity problems ({list.Count}):\n" + string.Join("\n", list.Take(50))); } } @@ -176,7 +176,7 @@ namespace Elwig.Helpers { } if (list.Count != 1 || list[0] != "ok") { - throw new FileFormatException($"Integrity problems ({list.Count}):\n" + string.Join("\n", list.Take(50))); + throw new DatabaseIntegrityException($"Integrity problems ({list.Count}):\n" + string.Join("\n", list.Take(50))); } } @@ -194,7 +194,7 @@ namespace Elwig.Helpers { } if (list.Count > 0) { - throw new InvalidDataException($"Foreign key violations ({list.Count}):\n" + string.Join("\n", list.Take(50) + throw new DatabaseForeignKeyViolationException($"Foreign key violations ({list.Count}):\n" + string.Join("\n", list.Take(50) .Select(v => $"{v.Table} - {v.RowId} - {v.Parent} - {v.FkId}"))); } } diff --git a/Elwig/Helpers/Printing/PdfPrinter.cs b/Elwig/Helpers/Printing/PdfPrinter.cs index a83a65b..d498c45 100644 --- a/Elwig/Helpers/Printing/PdfPrinter.cs +++ b/Elwig/Helpers/Printing/PdfPrinter.cs @@ -8,7 +8,7 @@ namespace Elwig.Helpers.Printing { public string PrinterName { get; init; } public PdfPrinter(string? printerName = null) { - PrinterName = printerName ?? GetDefaultPrinterName() ?? throw new InvalidOperationException("No default Windows printer is configured."); + PrinterName = printerName ?? GetDefaultPrinterName() ?? throw new ApplicationException("Kein Standard-Drucker in Windows festgelegt."); } public void Print(string pdfPath, int copies = 1, bool doublePaged = false) { diff --git a/Elwig/Helpers/Weighing/WeighingException.cs b/Elwig/Helpers/Weighing/WeighingException.cs deleted file mode 100644 index c49037d..0000000 --- a/Elwig/Helpers/Weighing/WeighingException.cs +++ /dev/null @@ -1,6 +0,0 @@ -using System; - -namespace Elwig.Helpers.Weighing { - public class WeighingException(string? message = null) : Exception(message) { - } -} diff --git a/Elwig/Services/InteractionService.cs b/Elwig/Services/InteractionService.cs index 8c15db0..9c3871e 100644 --- a/Elwig/Services/InteractionService.cs +++ b/Elwig/Services/InteractionService.cs @@ -1,7 +1,9 @@ +using iText.Commons.Exceptions; using Microsoft.Data.Sqlite; using Microsoft.Win32; using System; using System.Collections.Generic; +using System.IO; using System.Text.RegularExpressions; using System.Windows; @@ -118,6 +120,7 @@ namespace Elwig.Services { } public static void ShowException(string title, string? text, Exception exc, bool showExcType = false, bool isError = true) { + bool fatal = false; text = text == null ? "" : text + (text.EndsWith('.') || text.EndsWith('!') || text.EndsWith('?') ? "" : ":") + "\n\n"; if ((exc.InnerException ?? exc) is SqliteException sql) { if (sql.SqliteErrorCode == 5 || sql.SqliteErrorCode == 6) { @@ -145,10 +148,14 @@ namespace Elwig.Services { if (exc.InnerException != null) text += "\n\n" + exc.InnerException.Message; } } else { - text += exc.Message + (showExcType ? $" ({exc.GetType().Name})" : ""); + if (exc is SystemException and not FileNotFoundException and not OperationCanceledException and not FileFormatException and not IOException and not TimeoutException || exc is ITextException) { + text += "Schwerwiegender Fehler; unbedingt den Programmierern melden:\n\n"; + fatal = true; + } + text += exc.Message + (showExcType || fatal ? $" ({exc.GetType().Name})" : ""); if (exc.InnerException != null) text += "\n\n" + exc.InnerException.Message; } - if (App.Config.Debug && exc.StackTrace != null) { + if ((fatal || App.Config.Debug) && exc.StackTrace != null) { var m = Regex.Match(exc.StackTrace, @"\\([^:\\]*):line ([0-9]+)"); if (m != null) text += "\n\n" + m.Groups[1] + ": line " + m.Groups[2]; } @@ -167,7 +174,11 @@ namespace Elwig.Services { text = text == null ? "" : text + (text.EndsWith('.') || text.EndsWith('!') || text.EndsWith('?') ? "" : ":") + "\n\n"; text += exc.Message; if (exc.InnerException != null) text += "\n\n" + exc.InnerException.Message; - if (Override != null) { + if (NextError != null) { + NextError(title, text); + NextError = null; + return false; + } else if (Override != null) { return Override("error", title, text) != null; } else { return MessageBox.Show(text, title, MessageBoxButton.YesNo, MessageBoxImage.Error, MessageBoxResult.No) == MessageBoxResult.Yes; diff --git a/Elwig/Services/OrganicService.cs b/Elwig/Services/OrganicService.cs index 91ede7a..4a2fd5e 100644 --- a/Elwig/Services/OrganicService.cs +++ b/Elwig/Services/OrganicService.cs @@ -114,16 +114,16 @@ namespace Elwig.Services { return []; TracesCertificate[] certs = [.. jsonCerts.Select(j => new TracesCertificate { - Id = j!["reference"]?.GetValue() ?? throw new Exception(), - AuthorityCode = j["issuingBody"]?["code"]?.GetValue() ?? throw new Exception(), - OperatorId = j["operatorIdentifier"]?.GetValue() ?? throw new Exception(), - OperatorName = j["operator"]?["name"]?.GetValue() ?? throw new Exception(), - Activities = [.. j["activities"]?.AsArray().Select(a => Enum.Parse(a?["id"]?.GetValue().ToUpper().Replace("_IMPORT", "IMPORT") ?? throw new Exception())) ?? []], - CategoriesOfProduct = [.. j["categoriesOfProduct"]?.AsArray().Select(c => Enum.Parse(c?["id"]?.GetValue() ?? throw new Exception())) ?? []], - IssuedOn = DateOnly.FromDateTime(DateTime.ParseExact(j["issuedOn"]?.GetValue() ?? throw new Exception(), "yyyy-MM-ddTHH:mm:ss.fffK", CultureInfo.InvariantCulture, DateTimeStyles.None)), - ExpiresOn = DateOnly.ParseExact(j["expiresOn"]?.GetValue() ?? throw new Exception(), "yyyy-MM-dd"), - LastStatusUpdateOn = DateOnly.FromDateTime(DateTime.ParseExact(j["lastStatusUpdateDateTime"]?.GetValue() ?? throw new Exception(), "yyyy-MM-ddTHH:mm:ss.fffK", CultureInfo.InvariantCulture, DateTimeStyles.None)), - Status = Enum.Parse(j["status"]?["id"]?.GetValue() ?? throw new Exception()), + Id = j!["reference"]?.GetValue() ?? throw new KeyNotFoundException(), + AuthorityCode = j["issuingBody"]?["code"]?.GetValue() ?? throw new KeyNotFoundException(), + OperatorId = j["operatorIdentifier"]?.GetValue() ?? throw new KeyNotFoundException(), + OperatorName = j["operator"]?["name"]?.GetValue() ?? throw new KeyNotFoundException(), + Activities = [.. j["activities"]?.AsArray().Select(a => Enum.Parse(a?["id"]?.GetValue().ToUpper().Replace("_IMPORT", "IMPORT") ?? throw new KeyNotFoundException())) ?? []], + CategoriesOfProduct = [.. j["categoriesOfProduct"]?.AsArray().Select(c => Enum.Parse(c?["id"]?.GetValue() ?? throw new KeyNotFoundException())) ?? []], + IssuedOn = DateOnly.FromDateTime(DateTime.ParseExact(j["issuedOn"]?.GetValue() ?? throw new KeyNotFoundException(), "yyyy-MM-ddTHH:mm:ss.fffK", CultureInfo.InvariantCulture, DateTimeStyles.None)), + ExpiresOn = DateOnly.ParseExact(j["expiresOn"]?.GetValue() ?? throw new KeyNotFoundException(), "yyyy-MM-dd"), + LastStatusUpdateOn = DateOnly.FromDateTime(DateTime.ParseExact(j["lastStatusUpdateDateTime"]?.GetValue() ?? throw new KeyNotFoundException(), "yyyy-MM-ddTHH:mm:ss.fffK", CultureInfo.InvariantCulture, DateTimeStyles.None)), + Status = Enum.Parse(j["status"]?["id"]?.GetValue() ?? throw new KeyNotFoundException()), })]; return (!searchedByName || certs.Where(c => c.Status == TracesStatus.ISSUED).Select(c => c.OperatorId).ToHashSet().Count == 1) ? certs : []; diff --git a/Tests/UnitTests/ExportTests/ElwigDataTest.cs b/Tests/UnitTests/ExportTests/ElwigDataTest.cs index 30e53ba..7652242 100644 --- a/Tests/UnitTests/ExportTests/ElwigDataTest.cs +++ b/Tests/UnitTests/ExportTests/ElwigDataTest.cs @@ -202,9 +202,9 @@ namespace Tests.UnitTests.ExportTests { using (Assert.EnterMultipleScope()) { Assert.That(title, Is.EqualTo("Fehler beim Importieren")); Assert.That(text, Contains.Substring($""" - Die Elwig-Export-Datei '{Path.GetFileName(filename)}' konnte nicht verarbeitet werden und wird übersprungen: + Die Elwig-Export-Datei '{Path.GetFileName(filename)}' konnte nicht verarbeitet werden. Soll sie in Zukunft übersprungen werden? - No matching password found + Kein passendes Passwort gefunden """.Replace("\r\n", "\n"))); } }; diff --git a/Tests/UnitTests/WeighingTests/ScaleTestGrInzersdorfL246.cs b/Tests/UnitTests/WeighingTests/ScaleTestGrInzersdorfL246.cs index e78ab5a..e2d0699 100644 --- a/Tests/UnitTests/WeighingTests/ScaleTestGrInzersdorfL246.cs +++ b/Tests/UnitTests/WeighingTests/ScaleTestGrInzersdorfL246.cs @@ -1,3 +1,4 @@ +using Elwig.Helpers; using Elwig.Helpers.Weighing; namespace Tests.UnitTests.WeighingTests { diff --git a/Tests/UnitTests/WeighingTests/ScaleTestHaugsdorfDMA02.cs b/Tests/UnitTests/WeighingTests/ScaleTestHaugsdorfDMA02.cs index 0862c78..cc7dfc2 100644 --- a/Tests/UnitTests/WeighingTests/ScaleTestHaugsdorfDMA02.cs +++ b/Tests/UnitTests/WeighingTests/ScaleTestHaugsdorfDMA02.cs @@ -1,3 +1,4 @@ +using Elwig.Helpers; using Elwig.Helpers.Weighing; namespace Tests.UnitTests.WeighingTests { diff --git a/Tests/UnitTests/WeighingTests/ScaleTestMatzenIT3000A.cs b/Tests/UnitTests/WeighingTests/ScaleTestMatzenIT3000A.cs index 4fa9b1a..0feacfe 100644 --- a/Tests/UnitTests/WeighingTests/ScaleTestMatzenIT3000A.cs +++ b/Tests/UnitTests/WeighingTests/ScaleTestMatzenIT3000A.cs @@ -1,3 +1,4 @@ +using Elwig.Helpers; using Elwig.Helpers.Weighing; namespace Tests.UnitTests.WeighingTests { diff --git a/Tests/UnitTests/WeighingTests/ScaleTestSitzendorfDMA03Baby.cs b/Tests/UnitTests/WeighingTests/ScaleTestSitzendorfDMA03Baby.cs index 4ea1369..0b480b3 100644 --- a/Tests/UnitTests/WeighingTests/ScaleTestSitzendorfDMA03Baby.cs +++ b/Tests/UnitTests/WeighingTests/ScaleTestSitzendorfDMA03Baby.cs @@ -1,3 +1,4 @@ +using Elwig.Helpers; using Elwig.Helpers.Weighing; namespace Tests.UnitTests.WeighingTests { diff --git a/Tests/UnitTests/WeighingTests/ScaleTestWolkersdorfIT6000E.cs b/Tests/UnitTests/WeighingTests/ScaleTestWolkersdorfIT6000E.cs index 26788f8..b7366aa 100644 --- a/Tests/UnitTests/WeighingTests/ScaleTestWolkersdorfIT6000E.cs +++ b/Tests/UnitTests/WeighingTests/ScaleTestWolkersdorfIT6000E.cs @@ -1,3 +1,4 @@ +using Elwig.Helpers; using Elwig.Helpers.Weighing; namespace Tests.UnitTests.WeighingTests {