Backend internal error exception during ir lowering

I am creating a custom Checkbox within a Surface which has a Modifier.clickable: Surface( modifier = Modifier .clickable( enabled = enabled,

I am creating a custom Checkbox within a Surface which has a Modifier.clickable:

    Surface(
        modifier = Modifier
            .clickable(
                enabled = enabled,
                interactionSource = interactionSource,
                indication = rememberRipple(),
                role = Role.Checkbox,
                onClick = { onCheckedChange(!checked) }
            )
            .then(modifier),
    ) {
        Row {
            Checkbox(checked = checked, onCheckedChange = {}, colors = colors)
            Text(text = text ?: "")
        }
    }

When I try to build that, I get the Exception during IR lowering error error:

org.jetbrains.kotlin.backend.common.BackendException: Backend Internal error: Exception during IR lowering
File being compiled: /home/rene/AndroidStudioProjects/pass13/app/src/main/java/com/aresid/simplepasswordgeneratorapp/ui/widgets/Checkbox.kt

See the full stacktrace here.

Removing the Modifier.clickable solves the build issue.

I already tried up-/downgrading some versions but nothing is working properly.
Currently, I am using those versions:

    ext.versions = [
            'compileSdk': 31,
            'targetSdk' : 30,
            'minSdk'    : 26,
            'kotlin'    : '1.5.30',
            'navigation': '2.3.5',
            'compose'   : '1.0.2'
    ]

Has anybody an idea how to fix that?

@olonho You were correct in your speculation that it was kotlin-serialization related, removing the kotlin-serialization plugin causes the build to succeed. How confident are we that the 1.4.21-2 build actually fixed the serialization issue?

Also, how old is the 0.0.0-vsync-build30 branch? Just a shot in the dark, but we did remove our usage of deepCopyWithSymbols from Compose on Wednesday night your time, so if the last merge from androidx/compose is more than 48 hours ago, it might be worth doing another merge and seeing if that fixes it.

Otherwise, sounds like perhaps this repro should be passed to the Kotlin serialization team?

I applied the following diff on top of @ejektaflex repository, got the same error message @ejektaflex did.

jsproch-macbookpro6:ComposeCrash jsproch$ git diff
diff --git a/build.gradle.kts b/build.gradle.kts
index 2bba432..5755ff3 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -2,12 +2,12 @@ import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
 import org.jetbrains.compose.compose
 
 plugins {
-    id("org.jetbrains.kotlin.jvm") version "1.4.21"
-    id("org.jetbrains.kotlin.plugin.serialization") version "1.4.21"
-    id("org.jetbrains.compose") version "0.3.0-build141"
+    id("org.jetbrains.kotlin.jvm") version "1.4.21-2"
+    id("org.jetbrains.kotlin.plugin.serialization") version "1.4.21-2"
+    id("org.jetbrains.compose") version "0.0.0-vsync-build30"
 }
 
-val kotlinVersion = "1.4.21"
+val kotlinVersion = "1.4.21-2"
 val ktorVersion = "1.5.0"
 
 repositories {
@@ -32,3 +32,12 @@ dependencies {
 
 }
 
+
+// Allow forcing of kotlin version
+tasks.withType(KotlinCompile::class.java).configureEach {
+    kotlinOptions {
+        freeCompilerArgs = freeCompilerArgs + listOf("-P", "plugin:androidx.compose.compiler.plugins.kotlin:suppressKotlinVersionCompatibilityCheck=true")
+    }
+}
+
+
diff --git a/gradlew b/gradlew
old mode 100644
new mode 100755

Issue

I am creating a custom Checkbox within a Surface which has a Modifier.clickable:

    Surface(
        modifier = Modifier
            .clickable(
                enabled = enabled,
                interactionSource = interactionSource,
                indication = rememberRipple(),
                role = Role.Checkbox,
                onClick = { onCheckedChange(!checked) }
            )
            .then(modifier),
    ) {
        Row {
            Checkbox(checked = checked, onCheckedChange = {}, colors = colors)
            Text(text = text ?: "")
        }
    }

When I try to build that, I get the Exception during IR lowering error error:

org.jetbrains.kotlin.backend.common.BackendException: Backend Internal error: Exception during IR lowering
File being compiled: /home/rene/AndroidStudioProjects/pass13/app/src/main/java/com/aresid/simplepasswordgeneratorapp/ui/widgets/Checkbox.kt

See the full stacktrace here.

Removing the Modifier.clickable solves the build issue.

I already tried up-/downgrading some versions but nothing is working properly.
Currently, I am using those versions:

    ext.versions = [
            'compileSdk': 31,
            'targetSdk' : 30,
            'minSdk'    : 26,
            'kotlin'    : '1.5.30',
            'navigation': '2.3.5',
            'compose'   : '1.0.2'
    ]

Has anybody an idea how to fix that?

Solution

So I got in touch with the JetBrains team via their issue tracker as @Philip Dukhov suggested and they solved my problem: https://youtrack.jetbrains.com/issue/KT-48815.

I was using kotlinCompilerExtensionVersion = versions.composeVersion in my app’s build.gradle file and this is incorrect. versions.composeVersion is something provided by Gradle but it seems to be deprecated. Oneself should manually write the version which they’re using there.

Answered By – René Jörg Spies

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Содержание

  1. Обработка ошибок в формате JSON со Spring Boot
  2. Exception during IR lowering #301
  3. Comments
  4. Footer

Обработка ошибок в формате JSON со Spring Boot

Часто при работе с микросервисами, построенными с помощью технологии Spring Boot, можно видеть стандартный вывод ошибок подобный этому:

Такой вывод может быть излишним и ненужным клиентам вашего сервиса. Если вы хотите упростить жизнь сторонним сервисам в случае ошибки, то как раз об этом и пойдет речь в данном посте.

Начнем мы с построения небольшого сервиса с одним контроллером. Наш сервис будет принимать запрос на получение пользователя и в случае успеха отдавать данные по пользователю. В случае провала к нам возвращается ошибка. Начнем с простого и далее в статье будем усовершенствовать проект.

Итак, первое, что нам понадобится, это пользователь:

Здесь я использовал библиотеку lombok. Аннотация Data подставляет геттеры и сеттеры в класс. Остальные аннотации добавляют пустой конструктор и конструктор с параметрами. Если вы хотите повторить данный пример у себя в IntelliJ Idea, то вам необходимо поставить галочку в пункте enable annotation processing, либо написать все руками.

Далее нам понадобится сервис (для краткости репозиторий создавать не будем):

Ну и, конечно, сам контроллер:

Итак, у нас есть почти полноценный сервис с пользователями. Запускаем его и смотрим.

При запросе на URL localhost:8080/user/1 нам возвращается json в таком формате:

Все отлично. Но что будет, если сделать запрос на URL localhost:8080/user/4 (у нас всего 3 пользователя)? Правильный ответ: мы получим статус 200 и ничего в ответе. Ситуация не особо приятная. Ошибки нет, но и запрашиваемого объекта тоже нет.

Давайте улучшим наш сервис и добавим в него выбрасывание ошибки в случае неудачи. Для начала создадим исключение:

Теперь добавим пробрасывание ошибки в сервис:

Сделаем перезапуск сервиса и снова посмотрим, что будет при запросе несуществующего пользователя:

Это уже лучше. Гораздо более информативно и код статуса не 200. Такую ситуацию клиент на своей стороне уже сможет успешно и легко обработать. Но, как говорится, есть один нюанс. Ошибки могут быть совершенно разными, и клиенту нашего сервиса придется ставить кучу условных операторов и исследовать, что у нас пошло не так и как это можно поправить. Получается немного грубо с нашей стороны.

Как раз для таких случаев и была придумана аннотация ResponseStatus. Подставим ее на место нашего исключения и на практике посмотрим, как это работает:

Повторим запрос и посмотрим результат:

Отлично! Код статуса и сообщение поменялись. Теперь клиент сможет определись по коду ответа причину ошибки и даже уточнить ее по полю message. Но все же есть проблема. Большинство полей клиенту могут быть просто не нужны. Например, код ответа как отдельное поле может быть излишним, поскольку мы его и так получаем с кодом ответа. С этим нужно что-то делать.

К счастью, со spring boot сделать последний шаг к нашему успешному оповещению об ошибке не так сложно.

Все, что для этого требуется, разобрать пару аннотаций и один класс:

  • Аннотация ExceptionHandler. Используется для обработки собственных и каких-то специфичных исключений. Далее в примере будет понятно, что это значит. На всякий случай ссылка на документацию.
  • Аннотация ControllerAdvice. Данная аннотация дает «совет» группе констроллеров по определенным событиям. В нашем случае — это обработка ошибок. По умолчанию применяется ко всем контроллерам, но в параметрах можно указать отпределенную группу. Подбронее тут.
  • Класс ResponseEntityExceptionHandler. Данный класс занимается обработкой ошибок. У него куча методов, название которых построенно по принципу handle + название исключения. Если мы хотим обработать какое-то базовое исключение, то наследуемся от этого класса и переопределяем нужный метод.

Давайте теперь посмотрим, как все это обЪединить и построить наше уникальное и неповторимое сообщение об ошибке:

Сделаем все тот же запрос и увидим статус ответа 404 и наше сообщение с единственным полем:

Аннотацию ResponseStatus над нашим исключением можно смело убирать.

В итоге у нас получилось приложение, в котором обработка ошибок настраивается максимально гибко и просто. Полный проект можно найти в репозитории github. Надеюсь, что все было просто и понятно. Спасибо за внимание и пишите комментарии! Буду рад вашим замечаниям и уточнениям!

Источник

Exception during IR lowering #301

I’ve been trying to get JetBrains Compose to work with my existing project, but it keeps on giving me this error:

This is with build 0.3.0-build141 and Kotlin 1.4.21 .
Attached is what GameRegistry.kt looks like.

The text was updated successfully, but these errors were encountered:

Please retry with Compose 0.0.0-vsync-build30 and Kotlin 1.4.21-2 .

I switched to those versions, and I get the same error. I did also verify that they were the correct versions, so yes it is still happening.

I don’t even see any Composable functions in that file you attached and Compose is not on your stack trace. This doesn’t preclude Compose from being the source of the problem, but it does mean that the source of the problem isn’t obvious.

The file you posted isn’t too useful because it doesn’t even build without the dependencies referenced in that file. Can you create a minimal repro project such that the same error occurs? That will allow us to investigate further.

@olonho You were correct in your speculation that it was kotlin-serialization related, removing the kotlin-serialization plugin causes the build to succeed. How confident are we that the 1.4.21-2 build actually fixed the serialization issue?

Also, how old is the 0.0.0-vsync-build30 branch? Just a shot in the dark, but we did remove our usage of deepCopyWithSymbols from Compose on Wednesday night your time, so if the last merge from androidx/compose is more than 48 hours ago, it might be worth doing another merge and seeing if that fixes it.

Otherwise, sounds like perhaps this repro should be passed to the Kotlin serialization team?

I applied the following diff on top of @ejektaflex repository, got the same error message @ejektaflex did.

It’s indeed the conflict between compose and kotlinx.serialization — because Compose copies the whole IR tree, serialization plugin gets incorrect accessors for some declarations.

In this particular case, the workaround is to remove any private var/val s ( GameRegistry.autoKey in the reproducer)

@sandwwraith I just checked with 0.3.0-build143 . We were previously copying the whole IR tree (using deepCopyWithSymbols ) but we have since removed all invocations of deepCopyWithSymbols , so I think we are no longer copying the entire tree, yet this crash is still occurring.

Where is kotlinx.serialization getting the incorrect accessors from? Is the Compose Compiler doing something wrong here? Intuitively it seems like both plugins get IR in and IR out, as long as the IR is well-formed when it comes out of the plugin, then the other plugin should be able to operate without issue. Is our plugin somehow producing illegal IR?

Since $serializer is a nested class, and autoKey is private var, when plugin generates instruction to read it, compiler automatically inserts access$getautoKey function. When the IR tree is later copied (?) or manipulated in some other way, bodies of functions generated by serialization plugin are not updated for some reason and refer old access function that is not present in tree anymore, generating various failures. I’m not sure which plugin is to blame — I’ve tried to manipulate IR as directly as possible in my previous fixes, but it is for some reason is not enough. I’ll continue to investigate; it would be nice if you look at this from your point of view and possibly find some clues to share with me.

Leland mentioned that if it is on the Compose side, the type remapping seems like a possible suspect.
The line it fails on is: assert(dispatchReceiverType. isSubtypeOfClass(originalDispatchReceiver.type.classOrNull!!)) so for some reason maybe the two types are the «same type» but just one hasn’t been remapped to the new symbol for that type.

Let us know if you find that Compose is somehow to blame. I imagine that as more and more plugins get written, weird compatibility bugs are going to become more common unless there is some sort of validator that plugin authors can run on their output to verify their plugin is producing acceptable code, because it’s still not clear who or why is responsible for this crash. Certainly some expectation is violated by one of the plugins.

Not sure if this is helpful and it’s the same root cause with this issue: I encounter the same stack trace crash when I try to refactor a method name or change its parameter type from non-null to nullable, only one special method has this problem.

The problem goes away after I execute clean task, but it comes back once I do the rename operation again.

My project doesn’t depend on kotlin serializer but it depends on Compose(Android).

LMK if you need more information.

versions:
kotlin: 1.4.21-2
compose: 1.0.0-alpha11

Currently it is prohibited to use Compose and Serialization at the same module. The WO is to put them to separate ones.

Are you referring to Gradle modules? If so, does this mean we must separate our project into two parts?
Say, a frontend module which uses Compose and a backend module that contains any other code, along with KSX?

@ejektaflex
yes, split into two parts. One with Compose and another with Serialization.

Sorry for posting here; it’s the first result that comes up when I search this error, but I got it from a completely different cause.

This line causes the error
suspend fun forEach(block: suspend (T) -> Unit) = processors.forEach(fun(t: T) < block(t) >)

This line fixes it
suspend fun forEach(block: suspend (T) -> Unit) = processors.forEach

This was with
kotlin version 1.5.21
kotlinx coroutine version1.5.1

@EyeOfMidas do you have the same issue in the plain Kotlin code? Do you have the same issue on Android?

@EyeOfMidas do you have the same issue in the plain Kotlin code? Do you have the same issue on Android?

This is plain Kotlin code. We’re writing a backend server using Ktor, so I don’t have an Android development environment. You can reproduce it like this:

@EyeOfMidas
Then this is not the right place to report such issue. Here we work on Desktop/Web versions of Compose framework.

Looks like you are trying to use Compose along with Serialization. They couldn’t be used in the same module. Try to move either of them to a separate one.

Newer versions of Compose would throw an error about it before compilation.

@akurasov I’m facing the problem too but I’m not using kotlin-serialization, please help me.

e: org.jetbrains.kotlin.backend.common.BackendException: Backend Internal error: Exception during IR lowering
File being compiled: /Users/username/Documents/workspace/MyApp/app/src/main/java/com/a/b/c/d/e/ForwardActivity.kt
The root cause java.lang.AssertionError was thrown at: org.jetbrains.kotlin.backend.common.ir.IrUtilsKt.copyValueParametersToStatic(IrUtils.kt:264)
at org.jetbrains.kotlin.backend.common.CodegenUtil.reportBackendException(CodegenUtil.kt:239)
at org.jetbrains.kotlin.backend.common.CodegenUtil.reportBackendException$default(CodegenUtil.kt:235)
at org.jetbrains.kotlin.backend.common.phaser.PerformByIrFilePhase.invokeSequential(performByIrFile.kt:68)
at org.jetbrains.kotlin.backend.common.phaser.PerformByIrFilePhase.invoke(performByIrFile.kt:55)
at org.jetbrains.kotlin.backend.common.phaser.PerformByIrFilePhase.invoke(performByIrFile.kt:41)
at org.jetbrains.kotlin.backend.common.phaser.NamedCompilerPhase.invoke(CompilerPhase.kt:96)
at org.jetbrains.kotlin.backend.common.phaser.CompositePhase.invoke(PhaseBuilders.kt:29)
at org.jetbrains.kotlin.backend.common.phaser.NamedCompilerPhase.invoke(CompilerPhase.kt:96)
at org.jetbrains.kotlin.backend.common.phaser.CompositePhase.invoke(PhaseBuilders.kt:22)
at org.jetbrains.kotlin.backend.common.phaser.NamedCompilerPhase.invoke(CompilerPhase.kt:96)
at org.jetbrains.kotlin.backend.common.phaser.CompilerPhaseKt.invokeToplevel(CompilerPhase.kt:43)
at org.jetbrains.kotlin.backend.jvm.JvmIrCodegenFactory.doGenerateFilesInternal(JvmIrCodegenFactory.kt:195)
at org.jetbrains.kotlin.backend.jvm.JvmIrCodegenFactory.generateModule(JvmIrCodegenFactory.kt:60)
at org.jetbrains.kotlin.codegen.KotlinCodegenFacade.compileCorrectFiles(KotlinCodegenFacade.java:35)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.generate(KotlinToJVMBytecodeCompiler.kt:331)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:123)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli$default(KotlinToJVMBytecodeCompiler.kt:58)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:170)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:52)
at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:92)
at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:44)
at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:98)
at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:434)
at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:120)
at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileIncrementally(IncrementalCompilerRunner.kt:357)
at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileIncrementally$default(IncrementalCompilerRunner.kt:299)
at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileImpl$rebuild

@Iridescentangle Without a minimal repro, we probably wouldn’t be able to make much progress understanding why you are running into an issue. Please post a minimal example project which demonstrates your issue.

@Iridescentangle Without a minimal repro, we probably wouldn’t be able to make much progress understanding why you are running into an issue. Please post a minimal example project which demonstrates your issue.

I think it’s difficult because I’m intergrating compose into current project , which means I bearly find the way to reproduce this problem 😓 I doubt there is something wrong the way I intergrated ,so I tried several times these days in different branches, but got same result.
BTW,the file mentioned above,was reported during the compiler exception. I checked this class ,there is no kotlin-serialization included (even not depended by the project),and I tried to remove the coroutines-anko library,but also not helping.

If this problem is reproduced without kotlinx-serialization, please use Kotlin’s issue tracker: https://youtrack.jetbrains.com/issues/KT

I think it’s difficult because I’m intergrating compose into current project , which means I bearly find the way to reproduce this problem 😓

Typically, I start by reproducing the problem in my project, then start deleting as much stuff as I can until the problem goes away. If deleting something causes the problem to go away, I undo that change (so the problem comes back) and delete something else. Repeat this process until I’m left with the minimal amount of code necessary to reproduce the issue.

I think it’s difficult because I’m intergrating compose into current project , which means I bearly find the way to reproduce this problem 😓

Typically, I start by reproducing the problem in my project, then start deleting as much stuff as I can until the problem goes away. If deleting something causes the problem to go away, I undo that change (so the problem comes back) and delete something else. Repeat this process until I’m left with the minimal amount of code necessary to reproduce the issue.

Sounds well , maybe it would take me a long time to do this 😄 because my project is a hodgepodge

@jimgoog
Hello bro, finally I found these codes which causes this exception,although I have no idea with the exact reason.I tried to comment out the codes of the file and finally found out these codes.
The repo I used is a popup library XPopup

@jimgoog I have no idea why it causes the exception,because it works well in the past.But if it became a problem ,I have to try other ways to solve this.So these codes look like this below

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Понравилась статья? Поделить с друзьями:
  • Backend error unable to complete ssl connection тарков ошибка
  • Backend error unable to complete ssl connection escape from tarkov
  • Backend error timeout error wildberries
  • Backend error ssl ca certificate error тарков
  • Backend error request timeout тарков