エラーを処理し、C#でバーコード操作をデバッグする方法
バーコード処理パイプラインは、エラーが発生しても何も通知されない場合があり、結果がゼロと表示されると"バーコードが存在しない"と誤解されることがよくあります。しかし、破損したファイル、パスワードで保護されたPDF、フォーマットの不一致などが原因となっている可能性があります。 適切なログ記録と構造化されたエラー処理を実装することで、これらの障害が明らかになり、実用的な診断情報が得られます。
IronBarcodeは、IronBarCode.Exceptions 名前空間内で型付きの例外階層を提供し、組み込みログAPIおよび詳細な BarcodeResult プロパティを提供します。 これらのプロパティには、検出されたフォーマット、デコードされた値、ページ番号、およびデコードが成功した各箇所の座標が含まれます。
このハウツーでは、型付き例外をキャッチして解釈する方法、失敗した読み取りからの診断コンテキストを抽出する方法、構造化ロギングを有効にする方法、バッチ操作中の失敗を分離する方法を説明します。
クイックスタート: バーコードエラーの処理と診断の有効化読み書き呼び出しを、IronBarcodeの型付き例外をターゲットにしたtry-catchブロックでラップし、静かな失敗の代わりに実行可能なエラーメッセージを表示します。
-
1Install IronBarcode with NuGet Package Manager
-
2このコード スニペットをコピーして実行します。
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}"); }C# -
3実際の環境でテストするためにデプロイする
今日プロジェクトで IronBarcode を使い始めましょう無料トライアル
IronBarcodeでバーコードエラーを処理し、診断機能を有効にする方法
- NuGetからIronBarcodeライブラリをダウンロード
- 特定の例外タイプをターゲットとしたtry-catchブロックで読み書き呼び出しをラップします
- 成功した読み取り後の
BarcodeResultsを検査し、空のエントリや信頼度の低いエントリを確認します IronSoftware.Loggerを有効にして内部の診断出力をキャプチャします- エラー続行ロジックを使用してバッチ操作でファイルごとに個別の失敗を隔離します
IronBarcodeの例外を捕捉して解釈するにはどうすればよいですか?
IronBarcodeの例外を、最も具体的なものから最も一般的なものまで捕捉します。 ファイルエラー、PDFパスワードエラー、エンコードエラーなど、処理が必要な例外を最初に処理するcatchブロックを配置し、その後に基本型を配置します。 IronBarCode.Exceptions 名前空間は11の例外タイプを定義し、それぞれが特定の失敗モードに対応しています:
| 例外タイプ | トリガー | 推奨される修正 |
|---|---|---|
IronBarCodeFileException | ファイルが破損しているか、ロックされているか、またはサポートされていない画像形式です。 | ファイルがサポートされている画像形式であり、ロックされていないことを検証します。また、ファイルが見つからない場合は、 FileNotFoundExceptionを別途キャッチします。 |
IronBarCodePdfPasswordException | PDFがパスワードで保護されているか暗号化されている | パスワードをPdfBarcodeReaderOptionsを通じて提供するか、ファイルをスキップしてログを記録します |
IronBarCodeEncodingException | バーコード生成中の一般的なエンコーディングエラー | 入力データが目的のBarcodeWriterEncoding制約と一致することを確認します |
IronBarCodeContentTooLongEncodingException | 選択されたシンボロジーで文字数制限を超える | データを切り詰めるか、より高容量のフォーマット(QR, DataMatrix)に切り替えます |
IronBarCodeFormatOnlyAcceptsNumericValuesEncodingException | 数値のみのフォーマット(EAN, UPC)に非数値文字を渡す | 入力をサニタイズするか、英数字フォーマット(Code128, Code39)に切り替えます |
IronBarCodeUnsupportedRendererEncodingException | 選択されたBarcodeEncodingはIronBarcodeで書き出せません | BarcodeEncodingの代わりにBarcodeWriterEncoding列挙型を使用します |
IronBarCodeParsingException | パース中に構造化データ(GS1-128)が検証に失敗する | パース前にCode128GS1Parser.IsValid()を使ってGS1構造を検証します |
IronBarCodeNativeException | ネイティブ相互運用層でのエラー(DLLが見つからない、プラットフォームの互換性) | プラットフォーム固有のNuGetパッケージがインストールされていることを確認します(BarCode.Linux, BarCode.macOS) |
IronBarCodeConfidenceThresholdException | 無効な信頼度しきい値引数がリーダーオプションに渡されている | ConfidenceThresholdが0.0から1.0の間であることを確認します |
IronBarCodeUnsupportedException | 現在のコンテキストではサポートされていない操作 | 変更履歴で、お使いのバージョンでの機能の利用可否を確認します |
IronBarCodeException | 基本タイプ — 上記に一致しないすべてのIronBarcode固有のエラーをキャッチします | 完全な例外詳細をログに記録し、調査のためにエスカレーションします |
例外フィルターをwhen節で使用して、深いネストなしで重複する例外タイプをルーティングします。 欠落したファイルは標準のIronBarCodeFileExceptionではなく、このケースのために別のキャッチブロックを含める必要があります:
入力
請求書番号をエンコードしたCode128バーコード(成功経路)と、欠落したPDFの内容を表す倉庫ラベルバーコード(失敗経路)。

scanned-invoice.png(成功パス)

warehouse-labels.pdf(エラー発生箇所:ディスク上にファイルが存在しません)
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 Try出力
![コンソール出力:Code128デコード成功を示す:[Code128] INV-2024-7829](/static-assets/barcode/how-to/detailed-error-messages/output-exception-hierarchy-success.webp)
ファイルが見つからない場合、FileNotFoundExceptionがトリガーされ、専用のキャッチブロックによってルーティングされます。

when (ex.Message.Contains("DLL"))フィルターは、依存関係が見つからないエラーを特定のハンドラーに送信し、他のネイティブ例外には影響を与えません。 この方法は、プラットフォーム固有のパッケージが不足している可能性があるDocker環境において特に有効です。
ライセンスキーが無効または欠落している場合には、IronSoftware.Exceptions.LicensingExceptionが別々にスローされます。 この例外は、個々の読み取りまたは書き込み呼び出しの前後ではなく、アプリケーションの起動時に捕捉してください。
読み取り失敗から診断の詳細を抽出するにはどうすればよいですか?
読み取り操作で結果がゼロ件返されることは例外ではありません。 空のBarcodeResultsコレクションが生成されます。 診断コンテキストは、入力パラメータ、設定済みオプション、および返された部分的な結果を検査することによって取得されます。
Points (隅の座標)を含みます。 結果が存在するが予期しない場合、まずPageNumberを確認してください。
入力
ReadingSpeed.Detailedで徹底的なスキャンを行います。

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 If出力
ExpectBarcodeTypes が画像のバーコードに一致する場合、読み取りはタイプ、値、ページ番号、位置を返します。
ExpectBarcodeTypesが実際のシンボロジーを含んでいない場合、読み取りは空の結果を返します。 [WARN] ブロックには、設定されたタイプ、読み取り速度、および推奨される次のアクションがログに記録されます。
![コンソール出力には、[WARN] Code128イメージに対してExpectBarcodeTypesがCode39に設定されているため、バーコードが見つかりませんでしたと表示されます。](/static-assets/barcode/how-to/detailed-error-messages/output-diagnostic-logging-failure.webp)
診断の過程で、2つの共通パターンが現れる。 狭いExpectBarcodeTypes設定のある空の結果は、通常バーコードが異なるシンボロジーを使用していることを意味します; BarcodeEncoding.Allに拡張することにより、このことを確認できます。 予期しないデコード結果は、通常、画質の悪さを示しています。
画像フィルターを適用し、読み込み速度を遅くして再試行すると、これらの問題は解決することがよくあります。 雑音の多い背景からの幽霊のような読み取りを排除するためにRemoveFalsePositiveオプションを切り替えることもできます。
バーコード操作の詳細ログを有効にするにはどうすればよいですか?
IronBarcodeはIronSoftware.Loggerを通じて組み込みのロギングAPIを提供しています。 読み取りおよび書き込みパイプラインからの内部診断出力を取得するには、バーコード操作を行う前にログモードとファイルパスを設定してください。
入力
詳細ログが有効になっている場合、読み取り対象としてCode128バーコードのTIFF画像が使用されます。

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.")LoggingModes.Allは、デバッグ出力とファイルレベルのロギングの両方をキャプチャします。 ログファイルには、画像の前処理段階、フォーマット検出の試行、ネイティブ相互運用呼び出しなど、公開APIからは見えない内部処理手順が記録されます。
構造化ロギング フレームワーク (Serilog、NLog、Microsoft.Extensions.Logging) を使用する生産パイプラインでは、IronBarcode操作をミドルウェアレイヤーでラップすることで、組み込みのログファイルの横に構造化JSONエントリを追加します。組み込みのロギングは、サポートエスカレーションのために役立つプレーンテキストの診断情報を記述します; 構造化されたラッパーは、オブザーバビリティスタックに対してクエリ可能なフィールドを提供する。
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 Function構造化された出力は、ログ集約ツールと直接統合されます。 コンテナ内の展開でFluentd、Datadog、またはCloudWatchにstdoutを接続します。 経過時間フィールドは、パフォーマンスの低下がSLA違反となる前にそれを明らかにする。
出力

バッチバーコード処理のデバッグ方法を教えてください
複数のファイルを処理するには、各読み込み処理を個別のtry-catchブロックで分離し、各ファイルの結果を記録し、集計サマリーを生成します。 パイプラインは最初のエラーで停止するのではなく、障害が発生しても処理を継続します。
入力
scans/バッチディレクトリからの5つのCode128バーコード画像のうちの4つ。 5番目のファイル(scan-05-broken.png)にはファイル例外をトリガーする無効なバイトが含まれています。

バッチ1 — スキャン1

バッチ1 — スキャン2

バッチ1 — スキャン3

バッチ1 — スキャン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}");
}
}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 If出力

実行中、コンソールにはデコードされたバーコードごとに1行が出力され、その後にファイル数、成功数、空の読み取り数、失敗数、経過時間を含む概要が表示されます。エラーは、対応するファイル名と失敗理由とともに一覧表示されます。
このプロセスでは、成功(バーコードが見つかり、デコードされた)、空(ファイルは読み取られたがバーコードが検出されなかった)、失敗(例外が発生した)の3つの結果カテゴリが区別されます。 この区別は重要です。なぜなら、空の読み取りとエラーには異なる対応が必要となるからです。 空の読み取りが発生する場合は、より広範なフォーマット設定が必要になる可能性があり、エラーが発生する場合は、ファイルの欠落、リソースのロック、ネイティブ依存関係の欠落など、インフラストラクチャの問題を示していることが多い。
エラーリストは、根本原因分析を支援するために、ファイルごとのコンテキストを保持します。 CI/CDパイプラインで、この出力を解析して終了コードを設定します。完全な成功の場合はゼロを、failCountがゼロより大きいときにはゼロ以外を設定するか、エラー詳細を警告システムに転送します。
より高いスループットを実現するためには、MaxParallelThreadsを使用可能なCPUコアに合わせて調整することで並列処理を有効にします。 並列反復をParallel.ForEachでラップし、スレッドセーフなコレクションをエラーリストに使用することで、ファイルごとの分離を維持します。
さらなる読み物
- IronBarcodeチュートリアル:バーコードの読み取り:エンドツーエンドの読み取り手順。 -偽陽性防止:ノイズの多い画像における誤検出を低減します。 -画像補正方法:読み取り精度を向上させるフィルター。
- Docker セットアップガイド:正しいネイティブ依存関係を用いたコンテナ化されたデプロイ。
- BarcodeReaderOptions APIリファレンス:完全な設定ドキュメント。
- IronBarcodeの変更履歴:バージョン固有の修正と機能追加。
パイプラインが本番稼働準備完了になったら、ライセンスオプションを確認してください。
よくある質問
IronBarcodeを使用してバーコード操作におけるエラーをどのように処理できますか?
IronBarcodeは型付き例外と組み込みロギングを提供し、バーコード操作におけるエラーを効率的に管理および処理し、アプリケーションのスムーズな動作を確保します。
バーコード問題をデバッグするためにIronBarcodeが提供する機能は何ですか?
IronBarcodeは診断の抽出と生産準備ができたバッチエラー分離を含み、無関係なバーコードタイプを無視することによりバーコード読み取りまでをより迅速かつ正確に行います。
IronBarcodeがバーコード処理中にエラーを記録できますか?
はい、IronBarcodeには組み込みのロギング機能があり、開発者はバーコード処理中のエラーの詳細をキャプチャして記録し、デバッグを容易にします。
IronBarcodeにおける型付き例外とは何ですか?
IronBarcodeの型付き例外は、バーコード操作の問題に関する詳細な情報を提供する特有のエラータイプであり、開発者が問題を診断し修正することを容易にします。
IronBarcodeはバッチエラー分離でどのように支援しますか?
IronBarcodeは生産準備ができたバッチエラー分離を提供し、エラーハンドリングにおいて、エラーニュースのあるバーコード操作を成功したものから分離し、バッチ処理におけるエラーマネジメントを簡略化します。
IronBarcodeを使用してバーコード操作から診断を抽出する方法がありますか?
はい、IronBarcodeは診断抽出ツールを提供し、開発者がバーコード操作の詳細情報を収集し、トラブルシューティングとエラー解決を支援します。
How can I catch and interpret exceptions effectively in IronBarcode?
Catch and interpret exceptions in IronBarcode by ordering your try-catch blocks from specific to general. Start with actionable exceptions like file errors or PDF password issues and end with the base IronBarCodeException to ensure comprehensive error handling.
What properties of BarcodeResult can be used for post-mortem analysis?
The BarcodeResult object in IronBarcode provides properties like BarcodeType, Value, PageNumber, and Points (coordinates) for post-mortem analysis. These properties help in understanding unexpected results by checking the actual versus expected barcode type and verifying the page number.
In IronBarcode, how can I prevent false positives during barcode reads?
To prevent false positives during barcode reads in IronBarcode, you can use image filters to enhance image quality and the RemoveFalsePositive option. Additionally, adjusting reading speed and ExpectBarcodeTypes can minimize errors from noisy backgrounds.
How does IronBarcode handle errors from encrypted PDFs?
IronBarcode handles errors from encrypted PDFs using the IronBarCodePdfPasswordException. To process such files, supply the password using PdfBarcodeReaderOptions or log and skip them for non-disruptive barcode processing.

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。