IRONSOFTWAREHOME

C#에서 QR 코드 오류 메시지를 처리하는 방법

Curtis Chau
Curtis Chau
Updated: 2026년 5월 9일

IronQR의 오류 처리 기능은 읽기 및 쓰기 실패를 포착하고, 진단 로그를 기록하며, 모든 스캔에서 명확한 결과를 얻을 수 있도록 도와줍니다. 명시적인 검사를 추가하지 않으면 결과가 비어 있거나 파일이 손상된 경우 모두 아무런 응답을 반환하지 않으므로 무엇이 잘못되었는지 알 수 없습니다. 특정 예외 처리 및 진단 로깅을 추가하면 조용히 발생하는 오류를 유용한 피드백으로 전환할 수 있습니다. 이 가이드에서는 빈 결과를 처리하는 방법, 쓰기 시간 예외를 관리하는 방법, 그리고 일괄 처리를 위한 구조화된 로깅 래퍼를 구축하는 방법을 설명합니다.

빠른 시작: QR 코드 오류 처리

try-catch 블록에 QR 읽기 작업을 포장하고 파일과 디코딩 실패에 대한 진단을 로그로 기록하세요.

  1. 1Install IronQR with NuGet Package Manager

    PM > Install-Package IronQR

  2. 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. 3실제 운영 환경에서 테스트할 수 있도록 배포하세요.

    무료 체험판으로 오늘 프로젝트에서 IronQR 사용 시작하기
    arrow pointer

읽기 오류 및 빈 결과 처리

로깅이 없으면 빈 결과와 손상된 파일이 호출자에게는 동일하게 보입니다. 다음 예제는 파일 접근 실패를 감지하고, 검사 결과가 없으면 경고를 표시합니다.

입력

이 QR 코드 예제 입력은 디스크에 있습니다. 우리는 두 가지 시나리오를 모두 시뮬레이션할 것입니다. 하나는 사용자가 파일을 가져와 디코딩하는 경우이고, 다른 하나는 파일 경로가 잘못된 경우입니다.

유효한 QR 코드 입력 인코딩 https://ironsoftware.com/qr/scan-1
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}");
}

산출

QR 코드 읽기가 성공적으로 완료되었음을 나타내는 터미널 출력에는 [QRCode] https://ironsoftware.com/qr/scan-1이 표시됩니다.
참고해 주세요: 성공적인 읽기는 QR 코드 값을 반환하며, 런타임 중 오류가 발생하면 아래에 표시된 예외 메시지 또는 경고가 표시됩니다.

아래 콘솔은 빈 결과 경우를 위한 [WARN]와 누락된 파일에 대한 [ERROR]를 보여주며, 각 파일 경로와 제안된 작업을 포함하고 있습니다.

터미널 출력에는 damaged-scan.png에서 QR 코드를 찾을 수 없다는 경고 메시지와 missing-label.png에 대한 파일을 찾을 수 없다는 오류가 표시됩니다.

쓰기 오류 처리

nullQrWriter.Write에 전달하면 IronQrEncodingException가 발생합니다. 설정된 오류 수정 수준 의 용량을 초과하는 데이터도 오류를 발생시킵니다. 오류 수정 수준이 높을수록 사용 가능한 데이터 용량이 줄어들기 때문입니다.

입력

아래 두 입력 변수는 실패 시나리오를 정의합니다: nullContentnull이고 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");
}

산출

콘솔에는 두 가지 오류 시나리오 모두에 대한 예외 유형과 메시지가 표시됩니다.

QrWriter.Write에 null 콘텐츠가 전달되어 IronQrEncodingException이 발생했음을 보여주는 터미널 출력입니다.

입력 길이와 예외 메시지를 기록하여 문제 해결에 더 짧은 콘텐츠가 필요한지 또는 더 낮은 수정 수준이 필요한지 파악합니다. 사용자 입력에 대해 인코딩 전에 문자열 길이를 검증하고 null 값을 확인하여 예외 발생률을 줄이고 진단 기능을 향상시키십시오.


QR 코드 작업 로깅

내부 진단을 캡처하려면 IronSoftware.Logger을 사용하세요. 각 읽기 작업에 대해 파일 경로, 결과 개수 및 경과 시간을 JSON 형식으로 기록하는 헬퍼 함수를 ​​구현하여 전체 배치에 대한 명확한 출력을 보장하십시오.

입력

배치에는 qr-scans/에서 온 네 개의 유효한 QR 코드 이미지와 잘못된 바이트가 있는 다섯 번째 파일, scan-05-broken.png가 포함됩니다.

https://ironsoftware.com/qr/scan-1을 인코딩하는 QR 코드

스캔 1

https://ironsoftware.com/qr/scan-2를 인코딩하는 QR 코드

스캔 2

https://ironsoftware.com/qr/scan-3을 인코딩하는 QR 코드

스캔 3

https://ironsoftware.com/qr/scan-4를 인코딩하는 QR 코드

스캔 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");
C#

산출

콘솔에는 각 파일에 대한 JSON 로그 라인이 표시됩니다. 성공적인 읽기 4건과 손상된 파일에 대한 구조화된 오류 항목 1건, 그리고 배치 요약이 표시됩니다. IronSoftware.LoggerIronQR-debug.log에 동시에 내부 진단을 기입합니다. 전체 디버그 로그를 여기에서 다운로드할 수 있습니다.

터미널 출력에는 4건의 성공적인 읽기 작업과 1건의 오류에 대한 JSON 구조의 로그 라인 Plus 배치 완료 요약이 표시됩니다.

JSON 출력은 로그 집계 도구에 직접 전달됩니다: stdout을 컨테이너화된 환경에서 Fluentd, Datadog 또는 CloudWatch로 전송하십시오. ms 필드는 대기 시간 퇴보를 드러내며, 디버그 로그는 래퍼가 하지 않는 내부 처리 단계를 캡처합니다.


추가 자료

제품 출시 준비가 완료되면 라이선스 옵션을 확인하세요 .

여기를 클릭하여 DetailedErrorMessagesTest 콘솔 앱 프로젝트 전체를 다운로드하세요 .

자주 묻는 질문

C#에서 QR 코드 읽기/쓰기 작업을 디버깅하려면 어떻게 해야 합니까?

IronQR을 사용하여 QR 코드 읽기/쓰기 작업을 디버깅하려면 예외를 포착하고 진단을 기록하며 구조화된 출력을 통해 일괄 처리를 모니터링할 수 있습니다.

C#에서 QR 코드 처리 중 오류가 발생하면 어떻게 해야 합니까?

C#에서 QR 코드를 처리하는 동안 오류가 발생하면 IronQR을 사용하여 예외를 포착하고 처리하십시오. 이를 통해 문제를 효과적으로 식별하고 해결할 수 있습니다.

IronQR은 QR 코드 일괄 처리 모니터링을 어떻게 지원합니까?

IronQR은 구조화된 출력을 제공하여 QR 코드 일괄 처리에서의 오류나 비효율성을 식별하고 대처하는 데 도움을 주므로 일괄 처리 모니터링을 지원합니다.

IronQR은 QR 코드 작업에 대한 진단을 기록할 수 있습니까?

예, IronQR은 QR 코드 작업에 대한 성능과 오류를 추적하고 분석할 수 있도록 진단을 기록할 수 있습니다.

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를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

...
더 읽어보기

시작할 준비 되셨나요?

Nuget Downloads 74,386버전:2026.9방금 출시

지금 바로 30일 무료 체험판 키를 받으세요.
신용카드나 계정 생성은 필요하지 않습니다.
PDF용 C# NuGet 라이브러리
NuGet을 사용하여 설치하세요

버전: 2026.9

PM > Install-Package IronQR
nuget.org/packages/IronQR/
  1. 솔루션 탐색기에서 참조를 마우스 오른쪽 버튼으로 클릭하고 NuGet 패키지 관리를 선택합니다.
  2. 찾아보기를 선택하고 "IronQR"을 검색하세요.
  3. 패키지를 선택하고 설치하세요
C# PDF DLL
DLL 다운로드

버전: 2026.9

  1. IronQR을 다운로드하고 솔루션 디렉터리 내의 ~/Libs와 같은 위치에 압축을 푸세요.
  2. Visual Studio 솔루션 탐색기에서 참조를 마우스 오른쪽 버튼으로 클릭합니다. 찾아보기를 선택하고 "IronQR.dll"을 선택합니다.

라이선스 가격은 749달러 부터 시작합니다.

Key in blue circle

무료 30일 체험 키를 즉시 받으세요.

Your trial license will be sent to your email address

제한 없음. 100% 무제한 이용. 신용카드 불필요.

bullet_checked신용카드나 계정 생성은 필요하지 않습니다.제한 없음. 100% 무제한 이용. 신용카드 불필요.
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
무료 라이브 데모를 예약하세요
Booking Badge

전 세계 수백만 엔지니어들이 신뢰하는 제품입니다.

Iron Software의 고객 로고
부담 없는 무료 상담을 받아보세요
아래 양식을 작성하시거나 sales@ironsoftware.com으로 이메일을 보내주세요.
고객님의 정보는 항상 비밀로 유지됩니다.
전 세계 수백만 엔지니어들이 신뢰하는 제품입니다.
Iron Software의 고객 로고
지금 바로 30일 무료 체험판 키를 받으세요.
신용카드나 계정 생성은 필요하지 않습니다.