Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: update errorHandler to support the same classes as in Swift. #235

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions changes-for-exceptions-2.diff
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
diff --git a/core/src/main/java/com/segment/analytics/kotlin/core/Analytics.kt b/core/src/main/java/com/segment/analytics/kotlin/core/Analytics.kt
index 3c6ddbc..cf70141 100644
--- a/core/src/main/java/com/segment/analytics/kotlin/core/Analytics.kt
+++ b/core/src/main/java/com/segment/analytics/kotlin/core/Analytics.kt
@@ -8,6 +8,7 @@ import com.segment.analytics.kotlin.core.platform.plugins.ContextPlugin
import com.segment.analytics.kotlin.core.platform.plugins.SegmentDestination
import com.segment.analytics.kotlin.core.platform.plugins.StartupQueue
import com.segment.analytics.kotlin.core.platform.plugins.UserInfoPlugin
+import com.segment.analytics.kotlin.core.platform.plugins.logger.LogFilterKind
import com.segment.analytics.kotlin.core.platform.plugins.logger.SegmentLog
import com.segment.analytics.kotlin.core.platform.plugins.logger.log
import kotlinx.coroutines.*
@@ -83,7 +84,10 @@ open class Analytics protected constructor(
constructor(configuration: Configuration) : this(configuration,
object : CoroutineConfiguration {
override val store = Store()
- override val analyticsScope = CoroutineScope(SupervisorJob())
+ val exceptionHandler =
+ CoroutineExceptionHandler { coroutineContext, throwable ->
+ println("From: $coroutineContext caught: $throwable") }
+ override val analyticsScope = CoroutineScope(SupervisorJob()+exceptionHandler)
override val analyticsDispatcher : CloseableCoroutineDispatcher =
Executors.newCachedThreadPool().asCoroutineDispatcher()
override val networkIODispatcher : CloseableCoroutineDispatcher =
@@ -95,28 +99,32 @@ open class Analytics protected constructor(
// This function provides a default state to the store & attaches the storage and store instances
// Initiates the initial call to settings and adds default system plugins
internal fun build() {
- // because startup queue doesn't depend on a state, we can add it first
- add(SegmentLog())
- add(StartupQueue())
- add(ContextPlugin())
- add(UserInfoPlugin())
-
- // Setup store
- analyticsScope.launch(analyticsDispatcher) {
- store.also {
- // load memory with initial value
- it.provide(userInfo)
- it.provide(System.defaultState(configuration, storage))
+ try {
+ // because startup queue doesn't depend on a state, we can add it first
+ add(SegmentLog())
+ add(StartupQueue())
+ add(ContextPlugin())
+ add(UserInfoPlugin())
+
+ // Setup store
+ analyticsScope.launch(analyticsDispatcher) {
+ store.also {
+ // load memory with initial value
+ it.provide(userInfo)
+ it.provide(System.defaultState(configuration, storage))
+
+ // subscribe to store after state is provided
+ storage.subscribeToStore()
+ }

- // subscribe to store after state is provided
- storage.subscribeToStore()
- }
+ if (configuration.autoAddSegmentDestination) {
+ add(SegmentDestination())
+ }

- if (configuration.autoAddSegmentDestination) {
- add(SegmentDestination())
+ checkSettings()
}
-
- checkSettings()
+ } catch (t: Throwable) {
+ log("Error calling build(): $t")
}
}

diff --git a/core/src/main/java/com/segment/analytics/kotlin/core/platform/Mediator.kt b/core/src/main/java/com/segment/analytics/kotlin/core/platform/Mediator.kt
index c3a599c..55bfecf 100644
--- a/core/src/main/java/com/segment/analytics/kotlin/core/platform/Mediator.kt
+++ b/core/src/main/java/com/segment/analytics/kotlin/core/platform/Mediator.kt
@@ -51,7 +51,11 @@ internal class Mediator(internal var plugins: CopyOnWriteArrayList<Plugin> = Cop

fun applyClosure(closure: (Plugin) -> Unit) {
plugins.forEach {
- closure(it)
+ try {
+ closure(it)
+ } catch (t : Throwable) {
+ Analytics.segmentLog("Caught Exception while applying closure to plugin: $it: $t")
+ }
}
}

3 changes: 3 additions & 0 deletions copy-aar-to-migration-sample.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#! /bin/sh

cp android/build/outputs/aar/android-debug.aar ../sample-java-to-kotlin-migration/app/libs/analytics-kotlin.aar && echo "Copy successful!"
20 changes: 20 additions & 0 deletions core/src/main/java/com/segment/analytics/kotlin/core/Errors.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,26 @@
package com.segment.analytics.kotlin.core

import com.segment.analytics.kotlin.core.platform.plugins.logger.segmentLog
sealed class AnalyticsError(): Throwable() {
data class StorageUnableToCreate(override val message: String?): AnalyticsError()
data class StorageUnableToWrite(override val message: String?): AnalyticsError()
data class StorageUnableToRename(override val message: String?): AnalyticsError()
data class StorageUnableToOpen(override val message: String?): AnalyticsError()
data class StorageUnableToClose(override val message: String?): AnalyticsError()
data class StorageInvalid(override val message: String?): AnalyticsError()
data class StorageUnknown(override val message: String?, override val cause: Throwable?): AnalyticsError()
data class NetworkUnexpectedHTTPCode(override val message: String?): AnalyticsError()
data class NetworkServerLimited(override val message: String?): AnalyticsError()
data class NetworkServerRejected(override val message: String?): AnalyticsError()
data class NetworkUnknown(override val message: String?, override val cause: Throwable?): AnalyticsError()
data class NetworkInvalidData(override val message: String?): AnalyticsError()
data class JsonUnableToSerialize(override val message: String?, override val cause: Throwable?): AnalyticsError()
data class JsonUnableToDeserialize(override val message: String?, override val cause: Throwable?): AnalyticsError()
data class JsonUnknown(override val message: String?, override val cause: Throwable?): AnalyticsError()
data class PluginError(override val message: String?, override val cause: Throwable?): AnalyticsError()
data class EnrichmentError(override val message: String?): AnalyticsError()
data class SettingsFetchError(override val message: String?, override val cause: Throwable?): AnalyticsError()
}

/**
* Reports an internal error to the user-defined error handler.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ internal fun Analytics.fetchSettings(
log("Fetched Settings: $settingsString")
LenientJson.decodeFromString(settingsString)
} catch (ex: Exception) {
reportErrorWithMetrics(this, ex, "Failed to fetch settings",
reportErrorWithMetrics(this, AnalyticsError.SettingsFetchError(ex.message, ex), "Failed to fetch settings",
Telemetry.INVOKE_ERROR_METRIC, ex.stackTraceToString()) {
it["error"] = ex.toString()
it["writekey"] = writeKey
Expand Down
1 change: 1 addition & 0 deletions samples/kotlin-android-api21-app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
52 changes: 52 additions & 0 deletions samples/kotlin-android-api21-app/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'org.jetbrains.kotlin.plugin.serialization'
}

android {
namespace 'com.segment.analytics.next.kotlin_android_api21_app'
compileSdk 33

defaultConfig {
applicationId "com.segment.analytics.next.kotlin_android_api21_app"
minSdk 21
//noinspection ExpiredTargetSdkVersion
targetSdk 33
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
viewBinding true
}
}

dependencies {

implementation project(':android')
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'androidx.navigation:navigation-fragment-ktx:2.5.3'
implementation 'androidx.navigation:navigation-ui-ktx:2.5.3'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
21 changes: 21 additions & 0 deletions samples/kotlin-android-api21-app/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.segment.analytics.next.kotlin_android_api21_app

import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4

import org.junit.Test
import org.junit.runner.RunWith

import org.junit.Assert.*

/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.segment.analytics.next.kotlin_android_api21_app", appContext.packageName)
}
}
25 changes: 25 additions & 0 deletions samples/kotlin-android-api21-app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".SampleApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.AnalyticsAndroidNext">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.AnalyticsAndroidNext.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.segment.analytics.next.kotlin_android_api21_app

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.segment.analytics.next.kotlin_android_api21_app.databinding.FragmentFirstBinding

/**
* A simple [Fragment] subclass as the default destination in the navigation.
*/
class FirstFragment : Fragment() {

private val TAG = SampleApplication.TAG + "/FirstFragment"
private var _binding: FragmentFirstBinding? = null

// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {

_binding = FragmentFirstBinding.inflate(inflater, container, false)
return binding.root

}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)

binding.buttonFirst.setOnClickListener {
findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
}

binding.buttonTrack.setOnClickListener {
Log.d(TAG, "onViewCreated: trying to track")
SampleApplication.analytics.track("test-track")
}
}

override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.segment.analytics.next.kotlin_android_api21_app

import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import android.view.Menu
import android.view.MenuItem
import com.segment.analytics.next.kotlin_android_api21_app.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)

setSupportActionBar(binding.toolbar)

val navController = findNavController(R.id.nav_host_fragment_content_main)
appBarConfiguration = AppBarConfiguration(navController.graph)
setupActionBarWithNavController(navController, appBarConfiguration)

binding.fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
}

override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return when (item.itemId) {
R.id.action_settings -> true
else -> super.onOptionsItemSelected(item)
}
}

override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.nav_host_fragment_content_main)
return navController.navigateUp(appBarConfiguration)
|| super.onSupportNavigateUp()
}
}
Loading
Loading