IronQR의 오류 처리 기능은 읽기 및 쓰기 실패를 포착하고, 진단 로그를 기록하며, 모든 스캔에서 명확한 결과를 얻을 수 있도록 도와줍니다. 명시적인 검사를 추가하지 않으면 결과가 비어 있거나 파일이 손상된 경우 모두 아무런 응답을 반환하지 않으므로 무엇이 잘못되었는지 알 수 없습니다. 특정 예외 처리 및 진단 로깅을 추가하면 조용히 발생하는 오류를 유용한 피드백으로 전환할 수 있습니다. 이 가이드에서는 빈 결과를 처리하는 방법, 쓰기 시간 예외를 관리하는 방법, 그리고 일괄 처리를 위한 구조화된 로깅 래퍼를 구축하는 방법을 설명합니다.
빠른 시작: QR 코드 오류 처리
QR 읽기 작업을 try-catch 블록에 감싸고 파일 및 디코딩 실패에 대한 진단을 기록합니다.
NuGet 패키지 관리자를 사용하여 https://www.nuget.org/packages/IronQR 설치하기
PM > Install-Package IronQR
다음 코드 조각을 복사하여 실행하세요.
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}");
}
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
$vbLabelText $csharpLabel
산출
참고해 주세요읽기에 성공하면 QR 코드 값이 반환되고, 런타임 중 오류가 발생하면 아래와 같은 예외 메시지 또는 경고가 표시됩니다.
아래 콘솔에는 결과가 없는 경우 [WARN]가, 파일이 누락된 경우 [ERROR]가 표시되며, 각각에 대한 파일 경로와 권장 조치가 함께 제공됩니다.
쓰기 오류 처리
null을 QrWriter.Write로 전달하면 IronQrEncodingException가 트리거됩니다. 설정된 오류 수정 수준 의 용량을 초과하는 데이터도 오류를 발생시킵니다. 오류 수정 수준이 높을수록 사용 가능한 데이터 용량이 줄어들기 때문입니다.
입력
아래의 두 입력 변수는 오류 시나리오를 정의합니다: nullContent은 null이며, 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
$vbLabelText $csharpLabel
산출
콘솔에는 두 가지 오류 시나리오 모두에 대한 예외 유형과 메시지가 표시됩니다.
입력 길이와 예외 메시지를 기록하여 문제 해결에 더 짧은 콘텐츠가 필요한지 또는 더 낮은 수정 수준이 필요한지 파악합니다. 사용자 입력에 대해 인코딩 전에 문자열 길이를 검증하고 null 값을 확인하여 예외 발생률을 줄이고 진단 기능을 향상시키십시오.
QR 코드 작업 로깅
내부 진단 정보를 캡처하려면 IronSoftware.Logger을 사용하십시오. 각 읽기 작업에 대해 파일 경로, 결과 개수 및 경과 시간을 JSON 형식으로 기록하는 헬퍼 함수를 구현하여 전체 배치에 대한 명확한 출력을 보장하십시오.
입력
이 배치에는 qr-scans/의 유효한 QR 코드 이미지 4개와, 무효한 바이트가 포함된 다섯 번째 파일 scan-05-broken.png이 포함되어 있습니다.
using IronQr;
using IronSoftware.Drawing;
using System.Diagnostics;
// Enable shared Iron Software logging for internal diagnostics
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All;
IronSoftware.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");
Imports IronQr
Imports IronSoftware.Drawing
Imports System.Diagnostics
Imports System.IO
Imports System.Linq
' Enable shared Iron Software logging for internal diagnostics
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All
IronSoftware.Logger.LogFilePath = "ironqr-debug.log"
' Reusable wrapper for structured observability
Private Function ReadQrWithDiagnostics(ByVal filePath As String) As (IEnumerable(Of QrResult), Boolean, String)
Dim sw = Stopwatch.StartNew()
Try
Dim input = New QrImageInput(AnyBitmap.FromFile(filePath))
Dim 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, Nothing)
Catch ex As Exception
sw.Stop()
Dim error As String = $"{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(Of QrResult)(), False, error)
End Try
End Function
' Usage: process a batch with per-file isolation
Dim files As String() = Directory.GetFiles("qr-scans/", "*.png")
Dim ok As Integer = 0, fail As Integer = 0
For Each file As String In files
Dim result = ReadQrWithDiagnostics(file)
Dim results = result.Item1
Dim success = result.Item2
Dim error = result.Item3
If success AndAlso results.Any() Then
ok += 1
Else
fail += 1
End If
Next
Console.WriteLine($"\nBatch complete: {ok} success, {fail} failed/empty out of {files.Length} files")
$vbLabelText $csharpLabel
산출
콘솔에는 각 파일에 대한 JSON 로그 라인이 표시됩니다. 성공적인 읽기 4건과 손상된 파일에 대한 구조화된 오류 항목 1건, 그리고 배치 요약이 표시됩니다. IronSoftware.Logger은 동시에 IronQR-debug.log에 내부 진단 정보를 기록합니다. 전체 디버그 로그는 여기에서 다운로드할 수 있습니다.
생성된 JSON 출력은 로그 집계 도구로 직접 전송됩니다: 컨테이너화된 배포 환경에서 stdout을 Fluentd, Datadog 또는 CloudWatch로 파이프라인으로 전송합니다. ms 필드는 지연 시간 저하 현상을 표시하며, 디버그 로그는 래퍼가 기록하지 않는 내부 처리 단계를 캡처합니다.