From c1c317014002311874006f319b04121c88ef4672 Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Fri, 5 Jun 2026 09:05:03 +0200 Subject: magic: improve error handling --- cabinet/magic.cpp | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) (limited to 'cabinet/magic.cpp') diff --git a/cabinet/magic.cpp b/cabinet/magic.cpp index 08b3046..96b78a3 100644 --- a/cabinet/magic.cpp +++ b/cabinet/magic.cpp @@ -53,24 +53,35 @@ namespace cab return *this; } - auto magic::process(std::filesystem::path path) -> std::expected + auto magic::process(std::filesystem::path path) -> std::expected { - auto result = ::magic_file(m_cookie, path.native().c_str()); - if (!result) + return handle_result(::magic_file(m_cookie, path.native().c_str())); + } + + auto magic::process(int file_descriptor) -> std::expected + { + if (file_descriptor < 0) { - return std::unexpected{std::string{::magic_error(m_cookie)}}; + return std::unexpected{std::make_error_code(std::errc::invalid_argument)}; } - return result; + + return handle_result(::magic_descriptor(m_cookie, file_descriptor)); } - auto magic::process(int file_descriptor) -> std::expected + auto magic::handle_result(char const * result) -> std::expected { - auto result = ::magic_descriptor(m_cookie, file_descriptor); + auto errno_copy = errno; + if (!result) { - return std::unexpected{std::string{::magic_error(m_cookie)}}; + auto magic_errno = ::magic_errno(m_cookie); + if (!magic_errno && !errno) + { + return std::unexpected{std::make_error_code(std::errc::invalid_argument)}; + } } - return result; + + return std::string{result}; } auto swap(magic & lhs, magic & rhs) noexcept -> void -- cgit v1.2.3