From fd0bcd97e8a57e2fc98adcb0c533c88d844728d6 Mon Sep 17 00:00:00 2001 From: Sergei Zimmerman Date: Tue, 13 Jan 2026 00:50:42 +0300 Subject: [PATCH] libutil: Include std::error_code in the base class SystemError --- src/libutil/include/nix/util/error.hh | 38 ++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/src/libutil/include/nix/util/error.hh b/src/libutil/include/nix/util/error.hh index 542fc8559..17de21ce5 100644 --- a/src/libutil/include/nix/util/error.hh +++ b/src/libutil/include/nix/util/error.hh @@ -240,9 +240,39 @@ MakeError(UsageError, Error); MakeError(UnimplementedError, Error); /** - * To use in catch-blocks. + * To use in catch-blocks. Provides a convenience method to get the portable + * std::error_code. Use when you want to catch and check an error condition like + * no_such_file_or_directory (ENOENT) without ifdefs. */ -MakeError(SystemError, Error); +class SystemError : public Error +{ + std::error_code errorCode; + +public: + template + SystemError(std::errc posixErrNo, Args &&... args) + : Error(std::forward(args)...) + , errorCode(std::make_error_code(posixErrNo)) + { + } + + template + SystemError(std::error_code errorCode, Args &&... args) + : Error(std::forward(args)...) + , errorCode(errorCode) + { + } + + const std::error_code ec() const & + { + return errorCode; + } + + bool is(std::errc e) const + { + return errorCode == e; + } +}; /** * POSIX system error, created using `errno`, `strerror` friends. @@ -271,7 +301,7 @@ public: */ template SysError(int errNo, const Args &... args) - : SystemError("") + : SystemError(static_cast(errNo), "") , errNo(errNo) { auto hf = HintFmt(args...); @@ -332,7 +362,7 @@ public: */ template WinError(DWORD lastError, const Args &... args) - : SystemError("") + : SystemError(std::error_code(lastError, std::system_category()), "") , lastError(lastError) { auto hf = HintFmt(args...);