PosixApiException

This commit is contained in:
Andrew Golovashevich 2025-09-04 22:54:25 +03:00
parent 10ea159606
commit 12a96d502a

View File

@ -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 =
"<windows api exception errno=${this.errno}>"
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}]")
}
}
}
}