C#でQRコードのエラーメッセージを処理する方法
IronQRのエラー処理機能は、読み取りおよび書き込みの失敗を検知し、診断ログを出力し、すべてのスキャンから明確な結果を得るのに役立ちます。 明示的なチェックを追加しない場合、空の結果と破損したファイルの両方とも何も返さないため、何が問題だったのかがわかりません。 的を絞った例外処理と診断ログを追加することで、サイレントエラーを有用なフィードバックに変えることができます。 このガイドでは、空の結果を処理する方法、書き込み時の例外を管理する方法、およびバッチ処理用の構造化ログラッパーを構築する方法について説明します。
クイックスタート: QR コードエラーの処理QR読み取り操作をtry-catchブロックでラップし、ファイルおよびデコード失敗の診断をログに記録します。
-
1Install IronQR with NuGet Package Manager
-
2このコード スニペットをコピーして実行します。
using IronQr; using IronSoftware.Drawing; try { var input = new QrImageInput(AnyBitmap.FromFile("label.png")); var results = new QrReader().Read(input); Console.WriteLine($"Found {results.Count()} QR code(s)"); } catch (IOException ex) { Console.Error.WriteLine($"File error: {ex.Message}"); }C# -
3実際の環境でテストするためにデプロイする
今日プロジェクトで IronQR を使い始めましょう無料トライアル
最小限のワークフロー(5ステップ)
- QRコードのエラーハンドリングのためのIronQR C#ライブラリをダウンロードする
- QRの読み書き呼び出しを
try-catchブロックでラップします。 IOExceptionとArgumentExceptionを特定の失敗のためにキャッチする- 空の結果と例外の診断をログに記録する
- パイプラインの可観測性のために構造化されたJSONログを使用する
読み取りエラーと空の結果の処理
ログ記録がない場合、呼び出し元にとっては、空の結果と破損したファイルは同じように見える。 以下の例は、ファイルアクセスエラーを検出し、スキャンで結果が返されない場合は警告を発します。
入力
このQRコードの入力例はディスク上に存在します。 ユーザーがファイルを取得してデコードする場合と、ファイルパスが間違っている場合の2つのシナリオをシミュレーションします。

using IronQr;
using IronSoftware.Drawing;
string filePath = "damaged-scan.png";
try
{
// File-level failure throws IOException or FileNotFoundException
var inputBmp = AnyBitmap.FromFile(filePath);
var imageInput = new QrImageInput(inputBmp);
var reader = new QrReader();
IEnumerable<QrResult> results = reader.Read(imageInput);
if (!results.Any())
{
// Not an exception — but a diagnostic event worth logging
Console.Error.WriteLine($"[WARN] No QR codes found in: {filePath}");
Console.Error.WriteLine($" Action: Verify image quality or try a different scan");
}
else
{
foreach (QrResult result in results)
{
Console.WriteLine($"[{result.QrType}] {result.Value}");
}
}
}
catch (FileNotFoundException)
{
Console.Error.WriteLine($"[ERROR] File not found: {filePath}");
}
catch (IOException ex)
{
Console.Error.WriteLine($"[ERROR] Cannot read file: {filePath} — {ex.Message}");
}
catch (Exception ex)
{
Console.Error.WriteLine($"[ERROR] Unexpected failure reading {filePath}: {ex.GetType().Name} — {ex.Message}");
}Imports IronQr
Imports IronSoftware.Drawing
Module Module1
Sub Main()
Dim filePath As String = "damaged-scan.png"
Try
' File-level failure throws IOException or FileNotFoundException
Dim inputBmp = AnyBitmap.FromFile(filePath)
Dim imageInput = New QrImageInput(inputBmp)
Dim reader = New QrReader()
Dim results As IEnumerable(Of QrResult) = reader.Read(imageInput)
If Not results.Any() Then
' Not an exception — but a diagnostic event worth logging
Console.Error.WriteLine($"[WARN] No QR codes found in: {filePath}")
Console.Error.WriteLine(" Action: Verify image quality or try a different scan")
Else
For Each result As QrResult In results
Console.WriteLine($"[{result.QrType}] {result.Value}")
Next
End If
Catch ex As FileNotFoundException
Console.Error.WriteLine($"[ERROR] File not found: {filePath}")
Catch ex As IOException
Console.Error.WriteLine($"[ERROR] Cannot read file: {filePath} — {ex.Message}")
Catch ex As Exception
Console.Error.WriteLine($"[ERROR] Unexpected failure reading {filePath}: {ex.GetType().Name} — {ex.Message}")
End Try
End Sub
End Module出力
![QRコードの読み取りが成功したことを示すターミナル出力[QRCode] https://ironsoftware.com/qr/scan-1が表示されます。](/static-assets/qr/how-to/detailed-error-messages/success-output-qr.webp)
以下のコンソールは、空の結果の場合の[ERROR]を示しており、それぞれのファイルパスと推奨されるアクションがあります。

書き込みエラーの処理
IronQrEncodingExceptionがトリガーされます。 設定されたエラー訂正レベルの容量を超えるデータもエラーになります。これは、訂正レベルが高くなると、利用可能なデータ容量が減少するためです。
入力
以下の2つの入力変数は失敗シナリオを定義します。oversizedContentは最高の修正レベルでQR容量を超える5,000文字の文字列です。
using IronQr;
string? content = null; // null throws IronQrEncodingException
string oversizedContent = new string('A', 5000); // 5,000 chars exceeds QR capacity at Highest error correction level
// Scenario 1: null input
try
{
QrCode qr = QrWriter.Write(content); // Input
}
catch (Exception ex)
{
Console.Error.WriteLine($"[ERROR] Null content: {ex.GetType().Name} — {ex.Message}"); // Output
}
// Scenario 2: data exceeds QR capacity at the configured error correction level
try
{
var options = new QrOptions(QrErrorCorrectionLevel.Highest);
QrCode qr = QrWriter.Write(oversizedContent, options); // Input
}
catch (Exception ex)
{
Console.Error.WriteLine($"[ERROR] QR capacity exceeded: {ex.Message}"); // Output
Console.Error.WriteLine($" Input length: {oversizedContent.Length} chars");
Console.Error.WriteLine($" Action: Reduce content or lower error correction level");
}Imports IronQr
Dim content As String = Nothing ' Nothing throws IronQrEncodingException
Dim oversizedContent As String = New String("A"c, 5000) ' 5,000 chars exceeds QR capacity at Highest error correction level
' Scenario 1: null input
Try
Dim qr As QrCode = QrWriter.Write(content) ' Input
Catch ex As Exception
Console.Error.WriteLine($"[ERROR] Null content: {ex.GetType().Name} — {ex.Message}") ' Output
End Try
' Scenario 2: data exceeds QR capacity at the configured error correction level
Try
Dim options As New QrOptions(QrErrorCorrectionLevel.Highest)
Dim qr As QrCode = QrWriter.Write(oversizedContent, options) ' Input
Catch ex As Exception
Console.Error.WriteLine($"[ERROR] QR capacity exceeded: {ex.Message}") ' Output
Console.Error.WriteLine($" Input length: {oversizedContent.Length} chars")
Console.Error.WriteLine(" Action: Reduce content or lower error correction level")
End Try出力
コンソールには、両方の失敗シナリオにおける例外の種類とメッセージが表示されます。

例外メッセージとともに入力長さを記録し、問題がコンテンツの短縮または修正レベルの引き下げを必要とするかどうかを特定します。 ユーザー入力の場合、例外処理のオーバーヘッドを削減し、診断を改善するために、エンコード前に文字列の長さを検証し、null値をチェックしてください。
QRコード操作のログ記録
内部診断を取得するためにIronSoftware.Loggerを使用します。 各読み取り操作ごとに、ファイルパス、結果数、経過時間をJSON形式でログに記録するヘルパー関数を実装し、バッチ全体の出力が明確になるようにします。
入力
バッチにはscan-05-broken.pngが含まれています。

スキャン1

スキャン2

スキャン3

スキャン4
using IronQr;
using IronSoftware.Drawing;
using System.Diagnostics;
// Enable shared Iron Software logging for internal diagnostics
IronQr.Logging.Logger.LoggingMode = IronQr.Logging.Logger.LoggingModes.All;
IronQr.Logging.Logger.LogFilePath = "ironqr-debug.log";
// Reusable wrapper for structured observability
(IEnumerable<QrResult> Results, bool Success, string Error) ReadQrWithDiagnostics(string filePath)
{
var sw = Stopwatch.StartNew();
try
{
var input = new QrImageInput(AnyBitmap.FromFile(filePath));
var results = new QrReader().Read(input).ToList();
sw.Stop();
Console.WriteLine($"{{\"op\":\"qr_read\",\"file\":\"{Path.GetFileName(filePath)}\","
+ $"\"status\":\"ok\",\"count\":{results.Count},\"ms\":{sw.ElapsedMilliseconds}}}");
return (results, true, null);
}
catch (Exception ex)
{
sw.Stop();
string error = $"{ex.GetType().Name}: {ex.Message}";
Console.Error.WriteLine($"{{\"op\":\"qr_read\",\"file\":\"{Path.GetFileName(filePath)}\","
+ $"\"status\":\"error\",\"exception\":\"{ex.GetType().Name}\","
+ $"\"message\":\"{ex.Message}\",\"ms\":{sw.ElapsedMilliseconds}}}");
return (Enumerable.Empty<QrResult>(), false, error);
}
}
// Usage: process a batch with per-file isolation
string[] files = Directory.GetFiles("qr-scans/", "*.png");
int ok = 0, fail = 0;
foreach (string file in files)
{
var (results, success, error) = ReadQrWithDiagnostics(file);
if (success && results.Any()) ok++;
else fail++;
}
Console.WriteLine($"\nBatch complete: {ok} success, {fail} failed/empty out of {files.Length} files");
出力
コンソールには、各ファイルに関するJSONログ行が表示されます。正常に読み取れた4行と、破損したファイルに関する構造化エラーエントリが1行、そしてバッチの概要が表示されます。 IronQR-debug.logに同時に内部診断を書き込みます。完全なデバッグログはここからダウンロードできます。

JSON出力はログ集約ツールに直接供給されます。stdoutをFluentdやDatadog、CloudWatchにコンテナ化されたデプロイメントでパイプします。 msフィールドは遅延の回帰を浮き彫りにし、デバッグログはラッパーが捕捉しない内部処理のステップを記録します。
さらなる読み物
-エラー訂正レベル:エンコードレベルでQRコードの耐性を調整します。
- QRコードの読み取り方法:最初から最後までの読み取り手順。
- QRコード生成チュートリアル:スタイルとロゴを使用した生成。
- QrReader APIリファレンス:メソッドのシグネチャと注釈。
- QrWriter APIリファレンス:すべての
Writeオーバーロード。
制作準備が整ったら、ライセンスオプションをご確認ください。
完全なDetailedErrorMessagesTestコンソールアプリプロジェクトをダウンロードするには、こちらをクリックしてください。
よくある質問
C# で QR コードの読み取り/書き込み操作をどのようにデバッグできますか?
C# で QR コードの読み取り/書き込み操作をデバッグするには、IronQR を使用して例外をキャッチし、診断をログに記録し、構造化出力でバッチ処理を監視できます。
C# で QR コード処理中にエラーが発生した場合はどうすればいいですか?
C# で QR コード処理中にエラーが発生した場合は、IronQR を使用して例外をキャッチし処理してください。これにより、効果的に問題を特定し解決できます。
IronQR は QR コードのバッチ処理を監視するのにどのように役立ちますか?
IronQR は構造化出力を提供し、QR コードのバッチ処理中のエラーや非効率さを特定し、対処するのを助けます。
IronQR は QR コード操作の診断をログに記録できますか?
はい、IronQR は QR コード操作の診断をログに記録でき、C# アプリケーションのパフォーマンスとエラーを追跡して分析するのに役立ちます。
IronQR を使用した QR コード処理での一般的な例外は何ですか?
IronQR を使用した QR コード処理での一般的な例外には、読み取り不可能な QR コードや不正確な形式処理に関連する問題があり、C# コードで適切な例外処理を行うことで対処できます。
How can I improve error detection during QR code processing with IronQR?
Improve error detection by implementing logging that captures detailed information on file paths, operation status, result counts, and execution time. This data supports easier debugging and system observability.
Can IronQR's logging output be integrated with log aggregation tools?
Yes, the JSON output from IronQR can be fed directly into log aggregation tools such as Fluentd, Datadog, or CloudWatch, making it suitable for containerized deployments and enhancing monitoring capabilities.
What approach does IronQR suggest for handling batch QR code operations?
IronQR recommends processing each file in isolation, logging the results for each read operation to help identify errors, and providing a complete batch summary that tallies successes and failures.
How does IronQR assist in diagnosing file-level failures during QR code scans?
IronQR detects file-level failures like IOException and FileNotFoundException, providing descriptive error messages which can be logged to pinpoint issues such as incorrect file paths or unreadable files.
Why is it important to wrap QR read/write calls in try-catch blocks?
Wrapping read/write operations in try-catch blocks ensures that failures do not crash the application, allowing you to handle exceptions gracefully, log necessary diagnostics, and guide the user with useful messages.

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