C#에서 QR 코드 오류 메시지를 처리하는 방법
IronQR의 오류 처리 기능은 읽기 및 쓰기 실패를 포착하고, 진단 로그를 기록하며, 모든 스캔에서 명확한 결과를 얻을 수 있도록 도와줍니다. 명시적인 검사를 추가하지 않으면 결과가 비어 있거나 파일이 손상된 경우 모두 아무런 응답을 반환하지 않으므로 무엇이 잘못되었는지 알 수 없습니다. 특정 예외 처리 및 진단 로깅을 추가하면 조용히 발생하는 오류를 유용한 피드백으로 전환할 수 있습니다. 이 가이드에서는 빈 결과를 처리하는 방법, 쓰기 시간 예외를 관리하는 방법, 그리고 일괄 처리를 위한 구조화된 로깅 래퍼를 구축하는 방법을 설명합니다.
빠른 시작: QR 코드 오류 처리
try-catch 블록에 QR 읽기 작업을 포장하고 파일과 디코딩 실패에 대한 진단을 로그로 기록하세요.
-
NuGet 패키지 관리자를 사용하여 https://www.nuget.org/packages/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}"); } -
실제 운영 환경에서 테스트할 수 있도록 배포하세요.
무료 체험판으로 오늘 프로젝트에서 IronQR 사용 시작하기
최소 워크플로우(5단계)
- QR 코드 오류 처리용 IronQR C# 라이브러리 다운로드
- QR 읽기/쓰기 호출을
try-catch블록으로 감싸기 IOException및ArgumentException을 특정 실패에 대해 잡습니다- 빈 결과와 예외에 대한 진단을 기록합니다
- 파이프라인 관측 가능성을 위한 구조화된 JSON 로깅을 사용합니다
읽기 오류 및 빈 결과 처리
로깅이 없으면 빈 결과와 손상된 파일이 호출자에게는 동일하게 보입니다. 다음 예제는 파일 접근 실패를 감지하고, 검사 결과가 없으면 경고를 표시합니다.
입력
이 QR 코드 예제 입력은 디스크에 있습니다. 우리는 두 가지 시나리오를 모두 시뮬레이션할 것입니다. 하나는 사용자가 파일을 가져와 디코딩하는 경우이고, 다른 하나는 파일 경로가 잘못된 경우입니다.
:path=/static-assets/qr/content-code-examples/how-to/detailed-error-messages/read-diagnostics.cs
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
산출
아래 콘솔은 빈 결과 경우를 위한 [WARN]와 누락된 파일에 대한 [ERROR]를 보여주며, 각 파일 경로와 제안된 작업을 포함하고 있습니다.
쓰기 오류 처리
null을 QrWriter.Write에 전달하면 IronQrEncodingException가 발생합니다. 설정된 오류 수정 수준 의 용량을 초과하는 데이터도 오류를 발생시킵니다. 오류 수정 수준이 높을수록 사용 가능한 데이터 용량이 줄어들기 때문입니다.
입력
아래 두 입력 변수는 실패 시나리오를 정의합니다: nullContent은 null이고 oversizedContent은 QR의 최고 수정 수준에서 용량을 초과하는 5,000 문자 문자열입니다.
:path=/static-assets/qr/content-code-examples/how-to/detailed-error-messages/write-diagnostics.cs
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 형식으로 기록하는 헬퍼 함수를 구현하여 전체 배치에 대한 명확한 출력을 보장하십시오.
입력
배치에는 qr-scans/에서 온 네 개의 유효한 QR 코드 이미지와 잘못된 바이트가 있는 다섯 번째 파일, scan-05-broken.png가 포함됩니다.
스캔 1
스캔 2
스캔 3
스캔 4
:path=/static-assets/qr/content-code-examples/how-to/detailed-error-messages/logging-wrapper.cs
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");
Imports IronQr
Imports IronSoftware.Drawing
Imports System.Diagnostics
Imports System.IO
Imports System.Linq
' 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
Private Function ReadQrWithDiagnostics(filePath As String) As (Results As IEnumerable(Of QrResult), Success As Boolean, Error As 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.Results
Dim success = result.Success
Dim error = result.Error
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")
산출
콘솔에는 각 파일에 대한 JSON 로그 라인이 표시됩니다. 성공적인 읽기 4건과 손상된 파일에 대한 구조화된 오류 항목 1건, 그리고 배치 요약이 표시됩니다. IronSoftware.Logger은 IronQR-debug.log에 동시에 내부 진단을 기입합니다. 전체 디버그 로그를 여기에서 다운로드할 수 있습니다.
JSON 출력은 로그 집계 도구에 직접 전달됩니다: stdout을 컨테이너화된 환경에서 Fluentd, Datadog 또는 CloudWatch로 전송하십시오. ms 필드는 대기 시간 퇴보를 드러내며, 디버그 로그는 래퍼가 하지 않는 내부 처리 단계를 캡처합니다.
추가 자료
- 오류 정정 수준 : 인코딩 단계에서 QR 코드 복원력을 조정합니다.
- QR 코드 읽는 방법 : 처음부터 끝까지 단계별로 설명합니다.
- QR 코드 생성기 사용법 : 스타일링 및 로고를 사용한 생성.
- QRReader API 참조 : 메서드 시그니처 및 설명.
QrWriter API 참조: 모든
Write오버로드.
제품 출시 준비가 완료되면 라이선스 옵션을 확인하세요 .
자주 묻는 질문
C#에서 QR 코드 읽기/쓰기 작업을 디버깅하려면 어떻게 해야 합니까?
IronQR을 사용하여 QR 코드 읽기/쓰기 작업을 디버깅하려면 예외를 포착하고 진단을 기록하며 구조화된 출력을 통해 일괄 처리를 모니터링할 수 있습니다.
C#에서 QR 코드 처리 중 오류가 발생하면 어떻게 해야 합니까?
C#에서 QR 코드를 처리하는 동안 오류가 발생하면 IronQR을 사용하여 예외를 포착하고 처리하십시오. 이를 통해 문제를 효과적으로 식별하고 해결할 수 있습니다.
IronQR은 QR 코드 일괄 처리 모니터링을 어떻게 지원합니까?
IronQR은 구조화된 출력을 제공하여 QR 코드 일괄 처리에서의 오류나 비효율성을 식별하고 대처하는 데 도움을 주므로 일괄 처리 모니터링을 지원합니다.
IronQR은 QR 코드 작업에 대한 진단을 기록할 수 있습니까?
예, IronQR은 QR 코드 작업에 대한 성능과 오류를 추적하고 분석할 수 있도록 진단을 기록할 수 있습니다.
IronQR을 사용한 QR 코드 처리에서의 일반적인 예외는 무엇입니까?
IronQR과 함께하는 QR 코드 처리에서의 일반적인 예외에는 읽기 어려운 QR 코드와 잘못된 형식 처리에 관련된 문제가 포함되며, C# 코드에서의 적절한 예외 처리를 통해 이를 관리할 수 있습니다.

