From 12a96d502a58f9cf209468a55bae4ce8514d64cb Mon Sep 17 00:00:00 2001 From: Andrew Golovashevich Date: Thu, 4 Sep 2025 22:54:25 +0300 Subject: [PATCH] PosixApiException --- .../PosixApiException.kt | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 src/posixMain/kotlin/ru/landgrafhomyak/utility/kotlin_native_interop_stdlib_0/PosixApiException.kt diff --git a/src/posixMain/kotlin/ru/landgrafhomyak/utility/kotlin_native_interop_stdlib_0/PosixApiException.kt b/src/posixMain/kotlin/ru/landgrafhomyak/utility/kotlin_native_interop_stdlib_0/PosixApiException.kt new file mode 100644 index 0000000..3c55e6a --- /dev/null +++ b/src/posixMain/kotlin/ru/landgrafhomyak/utility/kotlin_native_interop_stdlib_0/PosixApiException.kt @@ -0,0 +1,68 @@ +package ru.landgrafhomyak.utility.kotlin_native_interop_stdlib_0 + +import kotlinx.cinterop.ExperimentalForeignApi +import kotlinx.cinterop.toKStringFromUtf8 +import platform.posix.strerror +import platform.posix.errno as getLastErrno + +public class PosixApiException : OsException { + private val errno: Int + private val nativeMessage: String? + + public constructor(errno: Int, nativeMessage: String?) : super() { + this.errno = errno + this.nativeMessage = nativeMessage + } + + public constructor(errno: Int, nativeMessage: String?, customMessage: String?) : super(customMessage) { + this.errno = errno + this.nativeMessage = nativeMessage + } + + public constructor(errno: Int, nativeMessage: String?, customMessage: String?, cause: Throwable?) : super(customMessage, cause) { + this.errno = errno + this.nativeMessage = nativeMessage + } + + public constructor(errno: Int, nativeMessage: String?, cause: Throwable?) : super(cause) { + this.errno = errno + this.nativeMessage = nativeMessage + } + + override fun toString(): String = + "" + + public companion object { + public fun throwFromLastWindowsErr(): Nothing { + throw this.formatFromLastWindowsErr() + } + + public fun throwFromWindowsErrCode(code: Int): Nothing { + throw this.formatFromWindowsErrCode(code) + } + + public fun formatFromLastWindowsErr(): PosixApiException = this.formatFromWindowsErrCode(getLastErrno) + + public fun formatFromWindowsErrCode(code: Int): PosixApiException { + var err = PosixApiException(errno = code, nativeMessage = null, customMessage = "[errno=${code}]") + try { + val nativeMessage = this.getNativeMessageByErrno(code) + err = PosixApiException(errno = code, nativeMessage = nativeMessage, "[errno=${err}] ${nativeMessage}") + } catch (newErr: Throwable) { + err.addSuppressed(newErr) + } + return err + } + + @OptIn(ExperimentalForeignApi::class) + public fun getNativeMessageByErrno(code: Int): String { + val raw = strerror(code) + if (raw != null) { + return raw.toKStringFromUtf8() + } else { + val strerrErrno = getLastErrno + throw PosixApiException(errno = strerrErrno, nativeMessage = null, "[errno=${strerrErrno}]") + } + } + } +} \ No newline at end of file