Jak radzić sobie z błędami i debugować operacje związane z kodami kreskowymi w języku C#
Procesy przetwarzania kodów kreskowych mogą zakończyć się niepowodzeniem bez wyświetlania komunikatu, a brak wyników jest często mylnie interpretowany jako „brak kodu kreskowego”. Przyczyną mogą być jednak takie problemy, jak uszkodzone pliki, pliki PDF chronione hasłem lub niezgodności formatów. Wdrożenie odpowiedniego logowania i ustrukturyzowanej obsługi błędów pozwala wykryć te awarie i zapewnia diagnostykę umożliwiającą podjęcie działań.
IronBarcode oferuje typowaną hierarchię wyjątków w przestrzeni nazw IronBarCode.Exceptions, wbudowane API logowania oraz szczegółowe właściwości BarcodeResult. Właściwości te obejmują wykryty format, zdekodowaną wartość, numer strony oraz współrzędne dla każdego pomyślnego dekodowania.
Ten przewodnik wyjaśnia, jak przechwytywać i interpretować typowane wyjątki, wyodrębniać kontekst diagnostyczny z nieudanych odczytów, włączać strukturalne logowanie i izolować błędy podczas operacji wsadowych.
Szybki start: Obsługa błędów kodów kreskowych i włączanie diagnostykiNależy otoczyć wywołania odczytu/zapisu blokami try-catch ukierunkowanymi na typowane wyjątki IronBarcode, aby wyświetlać komunikaty o błędach umożliwiające podjęcie działań zamiast cichych awarii.
-
1Zainstaluj IronBarcode z NuGet Package Manager
-
2Skopiuj i uruchom ten fragment kodu.
using IronBarCode; using IronBarCode.Exceptions; try { BarcodeResults results = BarcodeReader.Read("label.pdf"); Console.WriteLine($"Found {results.Count} barcode(s)"); } catch (IronBarCodeFileException ex) { Console.Error.WriteLine($"File error: {ex.Message}"); }Imports IronBarCode Imports IronBarCode.Exceptions Try Dim results As BarcodeResults = BarcodeReader.Read("label.pdf") Console.WriteLine($"Found {results.Count} barcode(s)") Catch ex As IronBarCodeFileException Console.Error.WriteLine($"File error: {ex.Message}") End TryImports IronBarCode Imports IronBarCode.Exceptions Try Dim results As BarcodeResults = BarcodeReader.Read("label.pdf") Console.WriteLine($"Found {results.Count} barcode(s)") Catch ex As IronBarCodeFileException Console.Error.WriteLine($"File error: {ex.Message}") End Try -
3Wdrożenie do testowania w środowisku produkcyjnym
Rozpocznij korzystanie z IronBarcode w swoim projekcie już dziś z darmową wersją próbną
Jak radzić sobie z błędami kodów kreskowych i włączyć diagnostykę za pomocą IronBarcode
- Pobrać bibliotekę IronBarcode z NuGet
- Otoczyć wywołania odczytu/zapisu blokami try-catch ukierunkowane na konkretne typy wyjątków
- Sprawdzić
BarcodeResultspod kątem pustych lub mało wiarygodnych wpisów po pomyślnym odczycie - Włączyć
IronSoftware.Logger, aby przechwytywać wewnętrzne dane diagnostyczne - Izolować awarie poszczególnych plików w operacjach wsadowych za pomocą logiki kontynuacji po błędzie
Jak wykrywać i interpretować wyjątki IronBarcode?
Przechwytywać wyjątki IronBarcode od najbardziej szczegółowych do najbardziej ogólnych. Bloki catch należy uporządkować tak, aby najpierw obsługiwały wyjątki wymagające podjęcia działań, takie jak błędy plików, haseł PDF i kodowania, a następnie wyjątki typu podstawowego. Przestrzeń nazw IronBarCode.Exceptions definiuje 11 typów wyjątków, z których każdy odpowiada określonemu trybowi awarii:
| Typ wyjątku | Wyzwalacz | Zalecana poprawka |
|---|---|---|
IronBarCodeFileException | Plik jest uszkodzony, zablokowany lub ma nieobsługiwany format obrazu | Sprawdzić, czy plik ma obsługiwany format obrazu i nie jest zablokowany; oddzielnie przechwytywać wyjątki FileNotFoundException dla brakujących plików |
IronBarCodePdfPasswordException | Plik PDF jest chroniony hasłem lub zaszyfrowany | Podać hasło za pomocą PdfBarcodeReaderOptions lub pominąć plik i odnotować to w dzienniku |
IronBarCodeEncodingException | Ogólny błąd kodowania podczas generowania kodów kreskowych | Sprawdzić, czy dane wejściowe są zgodne z ograniczeniami docelowego BarcodeWriterEncoding |
IronBarCodeContentTooLongEncodingException | Wartość przekracza limit znaków dla wybranej symboliki | Skróć dane lub zmienić format na o większej pojemności (QR, DataMatrix) |
IronBarCodeFormatOnlyAcceptsNumericValuesEncodingException | Znaki nienumeryczne przekazane do formatu obsługującego wyłącznie cyfry (EAN, UPC) | Oczyść dane wejściowe lub zmienić format na alfanumeryczny (Code128, Code39) |
IronBarCodeUnsupportedRendererEncodingException | Wybrany BarcodeEncoding nie może być generowany przez IronBarcode | Zastosować wyliczenie BarcodeWriterEncoding zamiast BarcodeEncoding |
IronBarCodeParsingException | Dane strukturalne (GS1-128) nie przechodzą walidacji podczas parsowania | Przed parsowaniem należy zweryfikować strukturę GS1 za pomocą funkcji Code128GS1Parser.IsValid(). |
IronBarCodeNativeException | Błąd w natywnej warstwie interoperacyjności (brakujące biblioteki DLL, niezgodność platform) | Sprawdzić, czy zainstalowane są pakiety NuGet specyficzne dla danej platformy (BarCode.Linux, BarCode.macOS) |
IronBarCodeConfidenceThresholdException | Przekazano nieprawidłowy argument progu pewności do opcji czytnika | Upewnij się, że wartość ConfidenceThreshold mieści się w przedziale od 0,0 do 1,0 |
IronBarCodeUnsupportedException | Operacja nieobsługiwana w bieżącym kontekście | Sprawdzić changelog, aby dowiedzieć się, jakie funkcje są dostępne w używanej wersji |
IronBarCodeException | Podstawowy typ - przechwytuje dowolny błąd specyficzny dla IronBarcode, który nie został wymieniony powyżej | Rejestrować pełne szczegóły wyjątków i przekazać je do dalszego zbadania |
Używać filtrów wyjątków z klauzulami when, aby skierować nakładające się typy wyjątków bez głębokiego zagnieżdżenia. Brakujące pliki zgłaszają standardowy System.IO.FileNotFoundException zamiast IronBarCodeFileException, więc osobny blok catch w tym przypadku jest zalecany:
Dane wejściowe
Kod kreskowy Code128 zawierający numer faktury (ścieżka sukcesu) oraz kod kreskowy etykiety magazynowej przedstawiający zawartość brakującego pliku PDF (ścieżka niepowodzenia).

scanned-invoice.png (ścieżka sukcesu)

warehouse-labels.pdf (ścieżka awarii - plik nieobecny na dysku)
using IronBarCode;
using IronBarCode.Exceptions;
// Success path: valid file present on disk
string filePath = "scanned-invoice.png";
// Failure path: file does not exist → caught by FileNotFoundException below
// string filePath = "warehouse-labels.pdf";
try
{
BarcodeResults results = BarcodeReader.Read(filePath);
foreach (BarcodeResult result in results)
{
// Print the detected symbology and decoded value for each barcode found
Console.WriteLine($"[{result.BarcodeType}] {result.Value}");
}
}
catch (IronBarCodePdfPasswordException ex)
{
// PDF is encrypted — supply the password via PdfBarcodeReaderOptions before retrying
Console.Error.WriteLine($"PDF requires password: {filePath} — {ex.Message}");
}
catch (IronBarCodeFileException ex)
{
// File is present but corrupted, locked, or in an unsupported format
Console.Error.WriteLine($"Cannot read file: {filePath} — {ex.Message}");
}
catch (FileNotFoundException ex)
{
// Missing files throw FileNotFoundException, not IronBarCodeFileException
Console.Error.WriteLine($"File not found: {filePath} — {ex.Message}");
}
catch (IronBarCodeNativeException ex) when (ex.Message.Contains("DLL"))
{
// The when filter routes only missing-DLL errors here; other native exceptions
// fall through to the IronBarCodeException block below
Console.Error.WriteLine($"Missing native dependency: {ex.Message}");
}
catch (IronBarCodeException ex)
{
// Base catch for any IronBarcode-specific error not matched by the blocks above
Console.Error.WriteLine($"IronBarcode error: {ex.GetType().Name} — {ex.Message}");
}using IronBarCode;
using IronBarCode.Exceptions;
// Success path: valid file present on disk
string filePath = "scanned-invoice.png";
// Failure path: file does not exist → caught by FileNotFoundException below
// string filePath = "warehouse-labels.pdf";
try
{
BarcodeResults results = BarcodeReader.Read(filePath);
foreach (BarcodeResult result in results)
{
// Print the detected symbology and decoded value for each barcode found
Console.WriteLine($"[{result.BarcodeType}] {result.Value}");
}
}
catch (IronBarCodePdfPasswordException ex)
{
// PDF is encrypted — supply the password via PdfBarcodeReaderOptions before retrying
Console.Error.WriteLine($"PDF requires password: {filePath} — {ex.Message}");
}
catch (IronBarCodeFileException ex)
{
// File is present but corrupted, locked, or in an unsupported format
Console.Error.WriteLine($"Cannot read file: {filePath} — {ex.Message}");
}
catch (FileNotFoundException ex)
{
// Missing files throw FileNotFoundException, not IronBarCodeFileException
Console.Error.WriteLine($"File not found: {filePath} — {ex.Message}");
}
catch (IronBarCodeNativeException ex) when (ex.Message.Contains("DLL"))
{
// The when filter routes only missing-DLL errors here; other native exceptions
// fall through to the IronBarCodeException block below
Console.Error.WriteLine($"Missing native dependency: {ex.Message}");
}
catch (IronBarCodeException ex)
{
// Base catch for any IronBarcode-specific error not matched by the blocks above
Console.Error.WriteLine($"IronBarcode error: {ex.GetType().Name} — {ex.Message}");
}Imports IronBarCode
Imports IronBarCode.Exceptions
' Success path: valid file present on disk
Dim filePath As String = "scanned-invoice.png"
' Failure path: file does not exist → caught by FileNotFoundException below
' Dim filePath As String = "warehouse-labels.pdf"
Try
Dim results As BarcodeResults = BarcodeReader.Read(filePath)
For Each result As BarcodeResult In results
' Print the detected symbology and decoded value for each barcode found
Console.WriteLine($"[{result.BarcodeType}] {result.Value}")
Next
Catch ex As IronBarCodePdfPasswordException
' PDF is encrypted — supply the password via PdfBarcodeReaderOptions before retrying
Console.Error.WriteLine($"PDF requires password: {filePath} — {ex.Message}")
Catch ex As IronBarCodeFileException
' File is present but corrupted, locked, or in an unsupported format
Console.Error.WriteLine($"Cannot read file: {filePath} — {ex.Message}")
Catch ex As FileNotFoundException
' Missing files throw FileNotFoundException, not IronBarCodeFileException
Console.Error.WriteLine($"File not found: {filePath} — {ex.Message}")
Catch ex As IronBarCodeNativeException When ex.Message.Contains("DLL")
' The when filter routes only missing-DLL errors here; other native exceptions
' fall through to the IronBarCodeException block below
Console.Error.WriteLine($"Missing native dependency: {ex.Message}")
Catch ex As IronBarCodeException
' Base catch for any IronBarcode-specific error not matched by the blocks above
Console.Error.WriteLine($"IronBarcode error: {ex.GetType().Name} — {ex.Message}")
End TryImports IronBarCode
Imports IronBarCode.Exceptions
' Success path: valid file present on disk
Dim filePath As String = "scanned-invoice.png"
' Failure path: file does not exist → caught by FileNotFoundException below
' Dim filePath As String = "warehouse-labels.pdf"
Try
Dim results As BarcodeResults = BarcodeReader.Read(filePath)
For Each result As BarcodeResult In results
' Print the detected symbology and decoded value for each barcode found
Console.WriteLine($"[{result.BarcodeType}] {result.Value}")
Next
Catch ex As IronBarCodePdfPasswordException
' PDF is encrypted — supply the password via PdfBarcodeReaderOptions before retrying
Console.Error.WriteLine($"PDF requires password: {filePath} — {ex.Message}")
Catch ex As IronBarCodeFileException
' File is present but corrupted, locked, or in an unsupported format
Console.Error.WriteLine($"Cannot read file: {filePath} — {ex.Message}")
Catch ex As FileNotFoundException
' Missing files throw FileNotFoundException, not IronBarCodeFileException
Console.Error.WriteLine($"File not found: {filePath} — {ex.Message}")
Catch ex As IronBarCodeNativeException When ex.Message.Contains("DLL")
' The when filter routes only missing-DLL errors here; other native exceptions
' fall through to the IronBarCodeException block below
Console.Error.WriteLine($"Missing native dependency: {ex.Message}")
Catch ex As IronBarCodeException
' Base catch for any IronBarcode-specific error not matched by the blocks above
Console.Error.WriteLine($"IronBarcode error: {ex.GetType().Name} — {ex.Message}")
End TryWynik
![Wynik wyświetlony w konsoli po pomyślnym zdekodowaniu Code128: [Code128] INV-2024-7829](/static-assets/barcode/how-to/detailed-error-messages/output-exception-hierarchy-success.webp)
Brakujący plik wyzwala FileNotFoundException, przekierowany przez dedykowany blok catch.

Filtr when (ex.Message.Contains("DLL")) na IronBarCodeNativeException kieruje błędy brakujących zależności do konkretnego mechanizmu obsługi bez wpływu na inne wyjątki natywne. Takie podejście jest szczególnie przydatne w przypadku wdrożeń Docker, gdzie może brakować pakietów specyficznych dla danej platformy.
IronSoftware.Exceptions.LicensingException jest zgłaszany osobno, gdy klucz licencyjny jest nieprawidłowy lub nie został podany. Wyłapuj ten wyjątek podczas uruchamiania aplikacji, a nie w trakcie poszczególnych wywołań odczytu lub zapisu.
Jak wyodrębnić szczegóły diagnostyczne z nieudanych odczytów?
Operacja odczytu, która zwraca zero wyników, nie jest wyjątkiem; produkuje pustą kolekcję BarcodeResults. Kontekst diagnostyczny uzyskuje się poprzez analizę parametrów wejściowych, skonfigurowanych opcji oraz wszelkich zwracanych wyników częściowych.
Obiekt BarcodeResult dostarcza właściwości przydatne do analizy post factum, w tym BarcodeType, Value, PageNumber i Points (współrzędne narożne). Jeśli wyniki są obecne, ale nieoczekiwane, należy najpierw sprawdzić BarcodeType względem oczekiwanego formatu i zweryfikować PageNumber.
Dane wejściowe
Kod kreskowy Code128 kodujący numer faktury, odczytany z ustawieniem ExpectBarcodeTypes na Code128 i QRCode, oraz ReadingSpeed.Detailed dla dokładnego skanowania.

using IronBarCode;
string filePath = "scanned-invoice.png";
// Configure the reader to narrow the search to specific symbologies and use
// a thorough scan pass — narrows false positives and improves decode accuracy
var options = new BarcodeReaderOptions
{
ExpectBarcodeTypes = BarcodeEncoding.Code128 | BarcodeEncoding.QRCode, // limit scan to known formats
Speed = ReadingSpeed.Detailed, // slower but more thorough — use ExtremeDetail for damaged images
ExpectMultipleBarcodes = true // scan the full image rather than stopping at the first match
};
BarcodeResults results = BarcodeReader.Read(filePath, options);
// An empty result is not an exception — it means no barcode matched the configured options
if (results == null || results.Count == 0)
{
// Log the configured options alongside the warning so the cause is immediately actionable
Console.Error.WriteLine($"[WARN] No barcodes found in: {filePath}");
Console.Error.WriteLine($" ExpectedTypes: {options.ExpectBarcodeTypes}");
Console.Error.WriteLine($" Speed: {options.Speed}");
Console.Error.WriteLine($" Action: Retry with ReadingSpeed.ExtremeDetail or broaden ExpectBarcodeTypes");
}
else
{
foreach (BarcodeResult result in results)
{
// Points contains the four corner coordinates of the barcode in the image;
// use the first corner as a representative position indicator
string pos = result.Points.Length > 0 ? $"{result.Points[0].X:F0},{result.Points[0].Y:F0}" : "N/A";
Console.WriteLine($"[{result.BarcodeType}] {result.Value} "
+ $"(Page: {result.PageNumber}, Position: {pos})");
}
}using IronBarCode;
string filePath = "scanned-invoice.png";
// Configure the reader to narrow the search to specific symbologies and use
// a thorough scan pass — narrows false positives and improves decode accuracy
var options = new BarcodeReaderOptions
{
ExpectBarcodeTypes = BarcodeEncoding.Code128 | BarcodeEncoding.QRCode, // limit scan to known formats
Speed = ReadingSpeed.Detailed, // slower but more thorough — use ExtremeDetail for damaged images
ExpectMultipleBarcodes = true // scan the full image rather than stopping at the first match
};
BarcodeResults results = BarcodeReader.Read(filePath, options);
// An empty result is not an exception — it means no barcode matched the configured options
if (results == null || results.Count == 0)
{
// Log the configured options alongside the warning so the cause is immediately actionable
Console.Error.WriteLine($"[WARN] No barcodes found in: {filePath}");
Console.Error.WriteLine($" ExpectedTypes: {options.ExpectBarcodeTypes}");
Console.Error.WriteLine($" Speed: {options.Speed}");
Console.Error.WriteLine($" Action: Retry with ReadingSpeed.ExtremeDetail or broaden ExpectBarcodeTypes");
}
else
{
foreach (BarcodeResult result in results)
{
// Points contains the four corner coordinates of the barcode in the image;
// use the first corner as a representative position indicator
string pos = result.Points.Length > 0 ? $"{result.Points[0].X:F0},{result.Points[0].Y:F0}" : "N/A";
Console.WriteLine($"[{result.BarcodeType}] {result.Value} "
+ $"(Page: {result.PageNumber}, Position: {pos})");
}
}Imports IronBarCode
Dim filePath As String = "scanned-invoice.png"
' Configure the reader to narrow the search to specific symbologies and use
' a thorough scan pass — narrows false positives and improves decode accuracy
Dim options As New BarcodeReaderOptions With {
.ExpectBarcodeTypes = BarcodeEncoding.Code128 Or BarcodeEncoding.QRCode, ' limit scan to known formats
.Speed = ReadingSpeed.Detailed, ' slower but more thorough — use ExtremeDetail for damaged images
.ExpectMultipleBarcodes = True ' scan the full image rather than stopping at the first match
}
Dim results As BarcodeResults = BarcodeReader.Read(filePath, options)
' An empty result is not an exception — it means no barcode matched the configured options
If results Is Nothing OrElse results.Count = 0 Then
' Log the configured options alongside the warning so the cause is immediately actionable
Console.Error.WriteLine($"[WARN] No barcodes found in: {filePath}")
Console.Error.WriteLine($" ExpectedTypes: {options.ExpectBarcodeTypes}")
Console.Error.WriteLine($" Speed: {options.Speed}")
Console.Error.WriteLine($" Action: Retry with ReadingSpeed.ExtremeDetail or broaden ExpectBarcodeTypes")
Else
For Each result As BarcodeResult In results
' Points contains the four corner coordinates of the barcode in the image;
' use the first corner as a representative position indicator
Dim pos As String = If(result.Points.Length > 0, $"{result.Points(0).X:F0},{result.Points(0).Y:F0}", "N/A")
Console.WriteLine($"[{result.BarcodeType}] {result.Value} " &
$"(Page: {result.PageNumber}, Position: {pos})")
Next
End IfImports IronBarCode
Dim filePath As String = "scanned-invoice.png"
' Configure the reader to narrow the search to specific symbologies and use
' a thorough scan pass — narrows false positives and improves decode accuracy
Dim options As New BarcodeReaderOptions With {
.ExpectBarcodeTypes = BarcodeEncoding.Code128 Or BarcodeEncoding.QRCode, ' limit scan to known formats
.Speed = ReadingSpeed.Detailed, ' slower but more thorough — use ExtremeDetail for damaged images
.ExpectMultipleBarcodes = True ' scan the full image rather than stopping at the first match
}
Dim results As BarcodeResults = BarcodeReader.Read(filePath, options)
' An empty result is not an exception — it means no barcode matched the configured options
If results Is Nothing OrElse results.Count = 0 Then
' Log the configured options alongside the warning so the cause is immediately actionable
Console.Error.WriteLine($"[WARN] No barcodes found in: {filePath}")
Console.Error.WriteLine($" ExpectedTypes: {options.ExpectBarcodeTypes}")
Console.Error.WriteLine($" Speed: {options.Speed}")
Console.Error.WriteLine($" Action: Retry with ReadingSpeed.ExtremeDetail or broaden ExpectBarcodeTypes")
Else
For Each result As BarcodeResult In results
' Points contains the four corner coordinates of the barcode in the image;
' use the first corner as a representative position indicator
Dim pos As String = If(result.Points.Length > 0, $"{result.Points(0).X:F0},{result.Points(0).Y:F0}", "N/A")
Console.WriteLine($"[{result.BarcodeType}] {result.Value} " &
$"(Page: {result.PageNumber}, Position: {pos})")
Next
End IfWynik
ExpectBarcodeTypes pasuje do kodu kreskowego na obrazku, odczyt zwraca typ, wartość, numer strony i pozycję.
Jeżeli ExpectBarcodeTypes nie zawiera rzeczywistej symboliki, odczyt zwraca pusty wynik. Blok [WARN] rejestruje skonfigurowane typy, prędkość odczytu oraz sugerowane dalsze działanie.
![Wynik konsoli pokazujący [WARN] brak znalezionych kodów kreskowych przy ustawieniu ExpectBarcodeTypes na Code39 dla obrazu Code128](/static-assets/barcode/how-to/detailed-error-messages/output-diagnostic-logging-failure.webp)
Podczas diagnostyki pojawiają się dwa typowe wzorce. Puste wyniki z wąskim ustawieniem ExpectBarcodeTypes często oznaczają, że kod kreskowy używa innej symboliki; rozszerzenie do BarcodeEncoding.All może to potwierdzić. Nieoczekiwane wyniki dekodowania zazwyczaj wskazują na niską jakość obrazu.
Zastosowanie filtrów obrazu i ponowna próba przy mniejszej prędkości czytania często rozwiązuje te problemy. Można również przełączać opcję RemoveFalsePositive, aby wyeliminować fałszywe pozytywy spowodowane zaszumionym tłem.
Jak włączyć szczegółowe logowanie dla operacji związanych z kodami kreskowymi?
IronBarcode udostępnia wbudowane API logowania przez IronSoftware.Logger. Przed rozpoczęciem jakichkolwiek operacji związanych z kodami kreskowymi należy ustawić tryb logowania i ścieżkę do pliku, aby przechwycić wewnętrzne dane diagnostyczne z potoków odczytu i zapisu.
Dane wejściowe
Obraz TIFF z kodem kreskowym Code128 używany jako cel odczytu przy włączonym szczegółowym logowaniu.

using IronBarCode;
// Enable IronBarcode's built-in logging — set BEFORE any read/write calls
// LoggingModes.All writes both debug output and file-level diagnostics
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All;
IronSoftware.Logger.LogFilePath = "ironbarcode-debug.log"; // path is relative to the working directory
// All subsequent operations will write internal processing steps to the log file:
// image pre-processing stages, format detection attempts, and native interop calls
var options = new BarcodeReaderOptions
{
Speed = ReadingSpeed.Detailed,
ExpectBarcodeTypes = BarcodeEncoding.All // scan for every supported symbology
};
BarcodeResults results = BarcodeReader.Read("problem-scan.tiff", options);
Console.WriteLine($"Read complete. Results: {results.Count}. See ironbarcode-debug.log for details.");using IronBarCode;
// Enable IronBarcode's built-in logging — set BEFORE any read/write calls
// LoggingModes.All writes both debug output and file-level diagnostics
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All;
IronSoftware.Logger.LogFilePath = "ironbarcode-debug.log"; // path is relative to the working directory
// All subsequent operations will write internal processing steps to the log file:
// image pre-processing stages, format detection attempts, and native interop calls
var options = new BarcodeReaderOptions
{
Speed = ReadingSpeed.Detailed,
ExpectBarcodeTypes = BarcodeEncoding.All // scan for every supported symbology
};
BarcodeResults results = BarcodeReader.Read("problem-scan.tiff", options);
Console.WriteLine($"Read complete. Results: {results.Count}. See ironbarcode-debug.log for details.");Imports IronBarCode
' Enable IronBarcode's built-in logging — set BEFORE any read/write calls
' LoggingModes.All writes both debug output and file-level diagnostics
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All
IronSoftware.Logger.LogFilePath = "ironbarcode-debug.log" ' path is relative to the working directory
' All subsequent operations will write internal processing steps to the log file:
' image pre-processing stages, format detection attempts, and native interop calls
Dim options As New BarcodeReaderOptions With {
.Speed = ReadingSpeed.Detailed,
.ExpectBarcodeTypes = BarcodeEncoding.All ' scan for every supported symbology
}
Dim results As BarcodeResults = BarcodeReader.Read("problem-scan.tiff", options)
Console.WriteLine($"Read complete. Results: {results.Count}. See ironbarcode-debug.log for details.")Imports IronBarCode
' Enable IronBarcode's built-in logging — set BEFORE any read/write calls
' LoggingModes.All writes both debug output and file-level diagnostics
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All
IronSoftware.Logger.LogFilePath = "ironbarcode-debug.log" ' path is relative to the working directory
' All subsequent operations will write internal processing steps to the log file:
' image pre-processing stages, format detection attempts, and native interop calls
Dim options As New BarcodeReaderOptions With {
.Speed = ReadingSpeed.Detailed,
.ExpectBarcodeTypes = BarcodeEncoding.All ' scan for every supported symbology
}
Dim results As BarcodeResults = BarcodeReader.Read("problem-scan.tiff", options)
Console.WriteLine($"Read complete. Results: {results.Count}. See ironbarcode-debug.log for details.")LoggingModes.All przechwytuje zarówno wyjście debugowania, jak i logowanie na poziomie plików. Plik dziennika rejestruje wewnętrzne etapy przetwarzania, takie jak etapy wstępnego przetwarzania obrazów, próby wykrywania formatu oraz natywne wywołania interoperacyjne, które nie są widoczne za pośrednictwem publicznego interfejsu API.
W potokach produkcyjnych korzystających z frameworków logowania strukturalnego (Serilog, NLog, Microsoft.Extensions.Logging), opakowanie operacji IronBarcode warstwą pośrednią dodaje strukturalne wpisy JSON obok wbudowanego pliku dziennika. Wbudowany dziennik zapisuje diagnostykę tekstową przydatną do przekazania problemu do pomocy technicznej; warstwa logowania strukturalnego udostępnia pola, które można przeszukiwać w narzędziach obserwowalności.
using IronBarCode;
using System.Diagnostics;
// Lightweight wrapper that adds structured JSON observability to every read call.
// Call this in place of BarcodeReader.Read wherever elapsed-time and status logging is needed.
BarcodeResults ReadWithDiagnostics(string filePath, BarcodeReaderOptions options)
{
var sw = Stopwatch.StartNew(); // start timing before the read so setup overhead is included
try
{
BarcodeResults results = BarcodeReader.Read(filePath, options);
sw.Stop();
// Emit a structured success entry to stdout — pipe to Fluentd, Datadog, or CloudWatch
Console.WriteLine($"{{\"file\":\"{filePath}\",\"status\":\"ok\","
+ $"\"count\":{results.Count},\"elapsed_ms\":{sw.ElapsedMilliseconds}}}");
return results;
}
catch (Exception ex)
{
sw.Stop();
// Emit a structured error entry to stderr with exception type, message, and elapsed time
Console.Error.WriteLine($"{{\"file\":\"{filePath}\",\"status\":\"error\","
+ $"\"exception\":\"{ex.GetType().Name}\",\"message\":\"{ex.Message}\","
+ $"\"elapsed_ms\":{sw.ElapsedMilliseconds}}}");
throw; // rethrow so the caller's catch blocks still handle the exception normally
}
}using IronBarCode;
using System.Diagnostics;
// Lightweight wrapper that adds structured JSON observability to every read call.
// Call this in place of BarcodeReader.Read wherever elapsed-time and status logging is needed.
BarcodeResults ReadWithDiagnostics(string filePath, BarcodeReaderOptions options)
{
var sw = Stopwatch.StartNew(); // start timing before the read so setup overhead is included
try
{
BarcodeResults results = BarcodeReader.Read(filePath, options);
sw.Stop();
// Emit a structured success entry to stdout — pipe to Fluentd, Datadog, or CloudWatch
Console.WriteLine($"{{\"file\":\"{filePath}\",\"status\":\"ok\","
+ $"\"count\":{results.Count},\"elapsed_ms\":{sw.ElapsedMilliseconds}}}");
return results;
}
catch (Exception ex)
{
sw.Stop();
// Emit a structured error entry to stderr with exception type, message, and elapsed time
Console.Error.WriteLine($"{{\"file\":\"{filePath}\",\"status\":\"error\","
+ $"\"exception\":\"{ex.GetType().Name}\",\"message\":\"{ex.Message}\","
+ $"\"elapsed_ms\":{sw.ElapsedMilliseconds}}}");
throw; // rethrow so the caller's catch blocks still handle the exception normally
}
}Imports IronBarCode
Imports System.Diagnostics
' Lightweight wrapper that adds structured JSON observability to every read call.
' Call this in place of BarcodeReader.Read wherever elapsed-time and status logging is needed.
Function ReadWithDiagnostics(filePath As String, options As BarcodeReaderOptions) As BarcodeResults
Dim sw As Stopwatch = Stopwatch.StartNew() ' start timing before the read so setup overhead is included
Try
Dim results As BarcodeResults = BarcodeReader.Read(filePath, options)
sw.Stop()
' Emit a structured success entry to stdout — pipe to Fluentd, Datadog, or CloudWatch
Console.WriteLine($"{{""file"":""{filePath}"",""status"":""ok"",""count"":{results.Count},""elapsed_ms"":{sw.ElapsedMilliseconds}}}")
Return results
Catch ex As Exception
sw.Stop()
' Emit a structured error entry to stderr with exception type, message, and elapsed time
Console.Error.WriteLine($"{{""file"":""{filePath}"",""status"":""error"",""exception"":""{ex.GetType().Name}"",""message"":""{ex.Message}"",""elapsed_ms"":{sw.ElapsedMilliseconds}}}")
Throw ' rethrow so the caller's catch blocks still handle the exception normally
End Try
End FunctionImports IronBarCode
Imports System.Diagnostics
' Lightweight wrapper that adds structured JSON observability to every read call.
' Call this in place of BarcodeReader.Read wherever elapsed-time and status logging is needed.
Function ReadWithDiagnostics(filePath As String, options As BarcodeReaderOptions) As BarcodeResults
Dim sw As Stopwatch = Stopwatch.StartNew() ' start timing before the read so setup overhead is included
Try
Dim results As BarcodeResults = BarcodeReader.Read(filePath, options)
sw.Stop()
' Emit a structured success entry to stdout — pipe to Fluentd, Datadog, or CloudWatch
Console.WriteLine($"{{""file"":""{filePath}"",""status"":""ok"",""count"":{results.Count},""elapsed_ms"":{sw.ElapsedMilliseconds}}}")
Return results
Catch ex As Exception
sw.Stop()
' Emit a structured error entry to stderr with exception type, message, and elapsed time
Console.Error.WriteLine($"{{""file"":""{filePath}"",""status"":""error"",""exception"":""{ex.GetType().Name}"",""message"":""{ex.Message}"",""elapsed_ms"":{sw.ElapsedMilliseconds}}}")
Throw ' rethrow so the caller's catch blocks still handle the exception normally
End Try
End FunctionStrukturalny wynik integruje się bezpośrednio z narzędziami do agregacji logów. Przekierować stdout do Fluentd, Datadog lub CloudWatch we wdrożeniu kontenerowym. Pole czasu, który upłynął, wskazuje spadki wydajności, zanim staną się naruszeniami SLA.
Wynik

Jak debugować wsadowe przetwarzanie kodów kreskowych?
Przetwarzać wiele plików, izolując każdy odczyt w osobnym bloku try-catch, rejestrując wyniki dla każdego pliku i generując zbiorcze podsumowanie. Potok kontynuuje działanie pomimo wystąpienia błędów, zamiast zatrzymywać się przy pierwszym błędzie.
Dane wejściowe
Cztery z pięciu obrazów kodu kreskowego Code128 z katalogu wsadu scans/. Piąty plik (scan-05-broken.png) zawiera nieprawidłowe bajty, aby wywołać wyjątek pliku.

Paczka 1 - Skan 1

Paczka 1 - Skan 2

Paczka 1 - Skan 3

Paczka 1 - Skan 4
using IronBarCode;
using IronBarCode.Exceptions;
using System.Diagnostics;
// Enable built-in logging for the entire batch run so internal processing steps
// are captured in the log file alongside the per-file console output
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All;
IronSoftware.Logger.LogFilePath = "batch-run.log";
// Collect all files in the directory — SearchOption.TopDirectoryOnly skips subdirectories
string[] files = Directory.GetFiles("scans/", "*.*", SearchOption.TopDirectoryOnly);
var options = new BarcodeReaderOptions
{
Speed = ReadingSpeed.Balanced, // balances throughput vs accuracy
ExpectBarcodeTypes = BarcodeEncoding.Code128 | BarcodeEncoding.QRCode, // limit to known formats
ExpectMultipleBarcodes = true // scan each file fully
};
// Three outcome counters: success (decoded), empty (read OK but no barcode found), fail (exception)
int successCount = 0;
int failCount = 0;
int emptyCount = 0;
var errors = new List<(string File, string Error)>(); // per-file error context for root cause analysis
var sw = Stopwatch.StartNew();
foreach (string file in files)
{
try
{
BarcodeResults results = BarcodeReader.Read(file, options);
// Empty result is not an exception — the file was read but contained no matching barcode
if (results == null || results.Count == 0)
{
emptyCount++;
errors.Add((file, "No barcodes detected")); // record so caller can adjust options
continue;
}
foreach (BarcodeResult result in results)
{
Console.WriteLine($"{Path.GetFileName(file)} | {result.BarcodeType} | {result.Value}");
}
successCount++;
}
catch (IronBarCodePdfPasswordException)
{
// PDF is password-protected — supply password via PdfBarcodeReaderOptions to recover
failCount++;
errors.Add((file, "Password-protected PDF"));
}
catch (IronBarCodeFileException ex)
{
// File is corrupted, locked, or in an unsupported image format
failCount++;
errors.Add((file, $"File error: {ex.Message}"));
}
catch (FileNotFoundException ex)
{
// File was in the directory listing but deleted before the read completed (race condition)
failCount++;
errors.Add((file, $"File not found: {ex.Message}"));
}
catch (IronBarCodeException ex)
{
// Catch-all for any other IronBarcode-specific errors not handled above
failCount++;
errors.Add((file, $"{ex.GetType().Name}: {ex.Message}"));
}
catch (Exception ex)
{
// Unexpected non-IronBarcode error — log the full type for investigation
failCount++;
errors.Add((file, $"Unexpected: {ex.GetType().Name}: {ex.Message}"));
}
}
sw.Stop();
// Summary report — parse failCount > 0 in CI/CD to set a non-zero exit code
Console.WriteLine("\n--- Batch Summary ---");
Console.WriteLine($"Total files: {files.Length}");
Console.WriteLine($"Success: {successCount}");
Console.WriteLine($"Empty reads: {emptyCount}");
Console.WriteLine($"Failures: {failCount}");
Console.WriteLine($"Elapsed: {sw.Elapsed.TotalSeconds:F1}s");
if (errors.Any())
{
Console.WriteLine("\n--- Error Details ---");
foreach (var (errorFile, errorMsg) in errors)
{
Console.Error.WriteLine($" {Path.GetFileName(errorFile)}: {errorMsg}");
}
}using IronBarCode;
using IronBarCode.Exceptions;
using System.Diagnostics;
// Enable built-in logging for the entire batch run so internal processing steps
// are captured in the log file alongside the per-file console output
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All;
IronSoftware.Logger.LogFilePath = "batch-run.log";
// Collect all files in the directory — SearchOption.TopDirectoryOnly skips subdirectories
string[] files = Directory.GetFiles("scans/", "*.*", SearchOption.TopDirectoryOnly);
var options = new BarcodeReaderOptions
{
Speed = ReadingSpeed.Balanced, // balances throughput vs accuracy
ExpectBarcodeTypes = BarcodeEncoding.Code128 | BarcodeEncoding.QRCode, // limit to known formats
ExpectMultipleBarcodes = true // scan each file fully
};
// Three outcome counters: success (decoded), empty (read OK but no barcode found), fail (exception)
int successCount = 0;
int failCount = 0;
int emptyCount = 0;
var errors = new List<(string File, string Error)>(); // per-file error context for root cause analysis
var sw = Stopwatch.StartNew();
foreach (string file in files)
{
try
{
BarcodeResults results = BarcodeReader.Read(file, options);
// Empty result is not an exception — the file was read but contained no matching barcode
if (results == null || results.Count == 0)
{
emptyCount++;
errors.Add((file, "No barcodes detected")); // record so caller can adjust options
continue;
}
foreach (BarcodeResult result in results)
{
Console.WriteLine($"{Path.GetFileName(file)} | {result.BarcodeType} | {result.Value}");
}
successCount++;
}
catch (IronBarCodePdfPasswordException)
{
// PDF is password-protected — supply password via PdfBarcodeReaderOptions to recover
failCount++;
errors.Add((file, "Password-protected PDF"));
}
catch (IronBarCodeFileException ex)
{
// File is corrupted, locked, or in an unsupported image format
failCount++;
errors.Add((file, $"File error: {ex.Message}"));
}
catch (FileNotFoundException ex)
{
// File was in the directory listing but deleted before the read completed (race condition)
failCount++;
errors.Add((file, $"File not found: {ex.Message}"));
}
catch (IronBarCodeException ex)
{
// Catch-all for any other IronBarcode-specific errors not handled above
failCount++;
errors.Add((file, $"{ex.GetType().Name}: {ex.Message}"));
}
catch (Exception ex)
{
// Unexpected non-IronBarcode error — log the full type for investigation
failCount++;
errors.Add((file, $"Unexpected: {ex.GetType().Name}: {ex.Message}"));
}
}
sw.Stop();
// Summary report — parse failCount > 0 in CI/CD to set a non-zero exit code
Console.WriteLine("\n--- Batch Summary ---");
Console.WriteLine($"Total files: {files.Length}");
Console.WriteLine($"Success: {successCount}");
Console.WriteLine($"Empty reads: {emptyCount}");
Console.WriteLine($"Failures: {failCount}");
Console.WriteLine($"Elapsed: {sw.Elapsed.TotalSeconds:F1}s");
if (errors.Any())
{
Console.WriteLine("\n--- Error Details ---");
foreach (var (errorFile, errorMsg) in errors)
{
Console.Error.WriteLine($" {Path.GetFileName(errorFile)}: {errorMsg}");
}
}Imports IronBarCode
Imports IronBarCode.Exceptions
Imports System.Diagnostics
' Enable built-in logging for the entire batch run so internal processing steps
' are captured in the log file alongside the per-file console output
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All
IronSoftware.Logger.LogFilePath = "batch-run.log"
' Collect all files in the directory — SearchOption.TopDirectoryOnly skips subdirectories
Dim files As String() = Directory.GetFiles("scans/", "*.*", SearchOption.TopDirectoryOnly)
Dim options As New BarcodeReaderOptions With {
.Speed = ReadingSpeed.Balanced, ' balances throughput vs accuracy
.ExpectBarcodeTypes = BarcodeEncoding.Code128 Or BarcodeEncoding.QRCode, ' limit to known formats
.ExpectMultipleBarcodes = True ' scan each file fully
}
' Three outcome counters: success (decoded), empty (read OK but no barcode found), fail (exception)
Dim successCount As Integer = 0
Dim failCount As Integer = 0
Dim emptyCount As Integer = 0
Dim errors As New List(Of (File As String, Error As String))() ' per-file error context for root cause analysis
Dim sw As Stopwatch = Stopwatch.StartNew()
For Each file As String In files
Try
Dim results As BarcodeResults = BarcodeReader.Read(file, options)
' Empty result is not an exception — the file was read but contained no matching barcode
If results Is Nothing OrElse results.Count = 0 Then
emptyCount += 1
errors.Add((file, "No barcodes detected")) ' record so caller can adjust options
Continue For
End If
For Each result As BarcodeResult In results
Console.WriteLine($"{Path.GetFileName(file)} | {result.BarcodeType} | {result.Value}")
Next
successCount += 1
Catch ex As IronBarCodePdfPasswordException
' PDF is password-protected — supply password via PdfBarcodeReaderOptions to recover
failCount += 1
errors.Add((file, "Password-protected PDF"))
Catch ex As IronBarCodeFileException
' File is corrupted, locked, or in an unsupported image format
failCount += 1
errors.Add((file, $"File error: {ex.Message}"))
Catch ex As FileNotFoundException
' File was in the directory listing but deleted before the read completed (race condition)
failCount += 1
errors.Add((file, $"File not found: {ex.Message}"))
Catch ex As IronBarCodeException
' Catch-all for any other IronBarcode-specific errors not handled above
failCount += 1
errors.Add((file, $"{ex.GetType().Name}: {ex.Message}"))
Catch ex As Exception
' Unexpected non-IronBarcode error — log the full type for investigation
failCount += 1
errors.Add((file, $"Unexpected: {ex.GetType().Name}: {ex.Message}"))
End Try
Next
sw.Stop()
' Summary report — parse failCount > 0 in CI/CD to set a non-zero exit code
Console.WriteLine(vbCrLf & "--- Batch Summary ---")
Console.WriteLine($"Total files: {files.Length}")
Console.WriteLine($"Success: {successCount}")
Console.WriteLine($"Empty reads: {emptyCount}")
Console.WriteLine($"Failures: {failCount}")
Console.WriteLine($"Elapsed: {sw.Elapsed.TotalSeconds:F1}s")
If errors.Any() Then
Console.WriteLine(vbCrLf & "--- Error Details ---")
For Each errorDetail In errors
Console.Error.WriteLine($" {Path.GetFileName(errorDetail.File)}: {errorDetail.Error}")
Next
End IfImports IronBarCode
Imports IronBarCode.Exceptions
Imports System.Diagnostics
' Enable built-in logging for the entire batch run so internal processing steps
' are captured in the log file alongside the per-file console output
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All
IronSoftware.Logger.LogFilePath = "batch-run.log"
' Collect all files in the directory — SearchOption.TopDirectoryOnly skips subdirectories
Dim files As String() = Directory.GetFiles("scans/", "*.*", SearchOption.TopDirectoryOnly)
Dim options As New BarcodeReaderOptions With {
.Speed = ReadingSpeed.Balanced, ' balances throughput vs accuracy
.ExpectBarcodeTypes = BarcodeEncoding.Code128 Or BarcodeEncoding.QRCode, ' limit to known formats
.ExpectMultipleBarcodes = True ' scan each file fully
}
' Three outcome counters: success (decoded), empty (read OK but no barcode found), fail (exception)
Dim successCount As Integer = 0
Dim failCount As Integer = 0
Dim emptyCount As Integer = 0
Dim errors As New List(Of (File As String, Error As String))() ' per-file error context for root cause analysis
Dim sw As Stopwatch = Stopwatch.StartNew()
For Each file As String In files
Try
Dim results As BarcodeResults = BarcodeReader.Read(file, options)
' Empty result is not an exception — the file was read but contained no matching barcode
If results Is Nothing OrElse results.Count = 0 Then
emptyCount += 1
errors.Add((file, "No barcodes detected")) ' record so caller can adjust options
Continue For
End If
For Each result As BarcodeResult In results
Console.WriteLine($"{Path.GetFileName(file)} | {result.BarcodeType} | {result.Value}")
Next
successCount += 1
Catch ex As IronBarCodePdfPasswordException
' PDF is password-protected — supply password via PdfBarcodeReaderOptions to recover
failCount += 1
errors.Add((file, "Password-protected PDF"))
Catch ex As IronBarCodeFileException
' File is corrupted, locked, or in an unsupported image format
failCount += 1
errors.Add((file, $"File error: {ex.Message}"))
Catch ex As FileNotFoundException
' File was in the directory listing but deleted before the read completed (race condition)
failCount += 1
errors.Add((file, $"File not found: {ex.Message}"))
Catch ex As IronBarCodeException
' Catch-all for any other IronBarcode-specific errors not handled above
failCount += 1
errors.Add((file, $"{ex.GetType().Name}: {ex.Message}"))
Catch ex As Exception
' Unexpected non-IronBarcode error — log the full type for investigation
failCount += 1
errors.Add((file, $"Unexpected: {ex.GetType().Name}: {ex.Message}"))
End Try
Next
sw.Stop()
' Summary report — parse failCount > 0 in CI/CD to set a non-zero exit code
Console.WriteLine(vbCrLf & "--- Batch Summary ---")
Console.WriteLine($"Total files: {files.Length}")
Console.WriteLine($"Success: {successCount}")
Console.WriteLine($"Empty reads: {emptyCount}")
Console.WriteLine($"Failures: {failCount}")
Console.WriteLine($"Elapsed: {sw.Elapsed.TotalSeconds:F1}s")
If errors.Any() Then
Console.WriteLine(vbCrLf & "--- Error Details ---")
For Each errorDetail In errors
Console.Error.WriteLine($" {Path.GetFileName(errorDetail.File)}: {errorDetail.Error}")
Next
End IfWynik

Podczas wykonywania konsola wyświetla jedną linię dla każdego zdekodowanego kodu kreskowego, a następnie podsumowanie zawierające liczbę plików, operacje zakończone powodzeniem, puste odczyty, operacje zakończone niepowodzeniem oraz czas, który upłynął. Błędy są wymienione wraz z odpowiadającymi im nazwami plików i przyczynami niepowodzenia.
Proces rozróżnia trzy kategorie wyników: sukces (znaleziono i zdekodowano kody kreskowe), pusty (odczytano plik, ale nie wykryto kodów kreskowych) oraz niepowodzenie (wygenerowano wyjątek). To rozróżnienie ma znaczenie, ponieważ puste odczyty i awarie wymagają różnych reakcji. Puste odczyty mogą wymagać szerszych ustawień formatu, podczas gdy błędy często wskazują na problemy infrastrukturalne, takie jak brakujące pliki, zablokowane zasoby lub brakujące zależności natywne.
Lista błędów zachowuje kontekst dla poszczególnych plików, aby ułatwić analizę przyczyn źródłowych. W potoku CI/CD należy przeanalizować te dane wyjściowe, aby ustawić kody wyjścia (zero dla pełnego sukcesu i inne niż zero, gdy failCount jest większe niż zero) lub przekazać szczegóły błędu do systemu alarmowego.
Aby uzyskać wyższą przepustowość, włącz przetwarzanie równoległe, ustawiając Multithreaded na true i dostosowując MaxParallelThreads do dostępnych rdzeni CPU. Zachować izolację operacji na poszczególnych plikach, opakowując iterację równoległą w Parallel.ForEach i użyć kolekcji bezpiecznej wątkowo dla listy błędów.
Więcej informacji
- Samouczki IronBarcode: Odczyt kodów kreskowych: Kompleksowe przewodniki odczytu.
- Zapobieganie fałszywym pozytywom: redukcja fałszywych pozytywów w zaszumionych obrazach.
- Instrukcja korekcji obrazu: filtry poprawiające dokładność odczytu.
- Przewodnik po konfiguracji Dockera: Wdrożenie kontenerowe z odpowiednimi zależnościami natywnymi.
- Dokumentacja API BarcodeReaderOptions: Kompleksowa dokumentacja konfiguracji.
- Changelog IronBarcode: Naprawy i dodatki do funkcji dla określonych wersji.
Sprawdzić opcje licencjonowania kiedy potok jest gotowy do produkcji.
Najczęściej zadawane pytania
Jak mogę obsługiwać błędy kodów kreskowych w C# za pomocą IronBarcode?
Możesz obsługiwać błędy kodów kreskowych w C# za pomocą IronBarcode, korzystając z jego hierarchii typizowanych wyjątków w przestrzeni nazw IronBarCode.Exceptions. Pozwala to na przechwytywanie określonych wyjątków związanych z błędami plików, hasłami PDF, problemami z kodowaniem i innymi. Wdrożenie strukturalnego logowania i wykorzystanie właściwości BarcodeResult pomaga w diagnozowaniu i izolowaniu problemów.
Jakie są niektóre typowe wyjątki rzucane przez IronBarcode?
IronBarcode może rzucać różne wyjątki, takie jak IronBarCodeFileException dla problemów związanych z plikami, IronBarCodePdfPasswordException dla PDF z hasłem oraz IronBarCodeEncodingException dla problemów z kodowaniem. Każdy typ wyjątku dostarcza szczegółowych informacji diagnostycznych, które pomagają rozwiązać specyficzne błędy napotkane podczas przetwarzania kodów kreskowych.
Jak włączyć logowanie diagnostyczne w IronBarcode?
Aby włączyć logowanie do diagnostyki w IronBarcode, ustaw tryb logowania i ścieżkę do pliku za pomocą IronSoftware.Logger przed jakimikolwiek operacjami na kodach kreskowych. Pozwala to uchwycić wewnętrzne kroki przetwarzania i pomaga w śledzeniu problemów poprzez zapisywanie logów do określonego pliku.
Co zrobić, jeśli operacja odczytu kodu kreskowego zwraca zero wyników w IronBarcode?
Jeśli operacja odczytu kodu kreskowego zwraca zero wyników w IronBarcode, oznacza to, że żaden kod kreskowy nie pasował do skonfigurowanych opcji. Sprawdź swoje parametry wejściowe i opcje, takie jak ExpectBarcodeTypes i ReadingSpeed, i rozważ rozszerzenie oczekiwań dotyczących symboliki lub dostosowanie prędkości odczytu dla dokładniejszego skanowania.
Czy IronBarcode może obsługiwać wyjątki związane z brakującymi natywnymi zależnościami?
Tak, IronBarcode obsługuje wyjątki związane z brakującymi natywnymi zależnościami poprzez IronBarCodeNativeException. Możesz filtrować te wyjątki, aby zidentyfikować brakujące pliki DLL lub zależności platformy, co jest szczególnie przydatne w środowiskach Docker.
Jak mogę debugować wsadowe przetwarzanie kodów kreskowych za pomocą IronBarcode?
Do debugowania wsadowego przetwarzania kodów kreskowych w IronBarcode, izoluj każdą operację odczytu w własnym bloku try-catch i przechwytuj błędy dla każdego pliku. To podejście zapewnia, że operacja wsadowa kontynuuje pomimo błędów i generuje podsumowanie, które obejmuje sukcesy, niepowodzenia i puste wyniki.
Jak mogę skutecznie przechwytywać i interpretować wyjątki w IronBarcode?
Przechwytuj i interpretuj wyjątki w IronBarcode, układając bloki try-catch od szczegółowych do ogólnych. Zacznij od wyjątków, które można szybko rozwiązać, takich jak błędy pliku lub problemy z hasłem do PDF, a zakończ na podstawowym IronBarCodeException, aby zapewnić kompleksową obsługę błędów.
Jakie właściwości BarcodeResult można wykorzystać do analizy po fakcie?
Obiekt BarcodeResult w IronBarcode dostarcza właściwości, takie jak BarcodeType, Value, PageNumber i Points (współrzędne) do analizy po fakcie. Te właściwości pomagają zrozumieć nieoczekiwane wyniki poprzez sprawdzenie rzeczywistego versus oczekiwanego typu kodu kreskowego i weryfikację numeru strony.
W IronBarcode, jak mogę zapobiec fałszywym pozytywom podczas odczytu kodów kreskowych?
Aby zapobiec fałszywym pozytywom podczas odczytów kodów kreskowych w IronBarcode, możesz używać filtrów obrazów do poprawy jakości obrazów i opcji RemoveFalsePositive. Dodatkowo, dostosowanie prędkości odczytu i ExpectBarcodeTypes może zminimalizować błędy z hałaśliwego tła.
Jak IronBarcode obsługuje błędy związane z zaszyfrowanymi plikami PDF?
IronBarcode obsługuje błędy z zaszyfrowanych plików PDF, korzystając z IronBarCodePdfPasswordException. Aby przetworzyć takie pliki, podaj hasło przy użyciu PdfBarcodeReaderOptions lub zaloguj je i pomiń dla niedestrukcyjnego przetwarzania kodu kreskowego.
Curtis Chau posiada tytuł licencjata z informatyki (Uniwersytet Carleton) i specjalizuje się w front-endowym rozwoju, z ekspertką w Node.js, TypeScript, JavaScript i React. Pasjonuje się tworzeniem intuicyjnych i estetycznie przyjemnych interfejsów użytkownika, Curtis cieszy się pracą z nowoczesnymi frameworkami i tworzeniem dobrze zorganizowanych, atrakcyjnych wizualnie podręczników.