// Copyright 2015-present 650 Industries. All rights reserved. package host.exp.exponent.exceptions import android.content.Context import android.provider.Settings import host.exp.exponent.kernel.ExponentErrorMessage import host.exp.exponent.network.ExponentNetwork import host.exp.expoview.Exponent import java.lang.Exception import java.net.ConnectException import java.net.SocketTimeoutException import java.net.UnknownHostException object ExceptionUtils { /** * Converts an exception into and ExponentErrorMessage, which contains both a user facing * error message and a developer facing error message. * Example: * ManifestException with * manifestUrl="exp://exp.host/@exponent/pomodoro" * originalException=UnknownHostException * * turns into: * * ExponentErrorMessage with * userErrorMessage="Could not load exp://exp.host/@exponent/pomodoro. Airplane mode is on." * developerErrorMessage="java.net.UnknownHostException: Unable to resolve host" **/ fun exceptionToErrorMessage(exception: Exception): ExponentErrorMessage { val context: Context = Exponent.instance.application val defaultResponse = ExponentErrorMessage.developerErrorMessage(exception.toString()) if (exception is ExponentException) { // Grab both the user facing message from ExponentException var message = exception.toString() // Append general exception error messages if applicable if (exception.originalException() != null) { val userErrorMessage = getUserErrorMessage(exception.originalException(), context) if (userErrorMessage != null) { message += " $userErrorMessage" } } return ExponentErrorMessage(message, exception.originalExceptionMessage()) } val userErrorMessage = getUserErrorMessage(exception, context) return if (userErrorMessage != null) { defaultResponse.addUserErrorMessage(userErrorMessage) } else { defaultResponse } } fun exceptionToErrorHeader(exception: Exception): String? { if (exception is ManifestException) { return exception.errorHeader } return null } private fun getUserErrorMessage(exception: Exception?, context: Context): String? { if (exception is UnknownHostException || exception is ConnectException) { if (isAirplaneModeOn(context)) { return "Airplane mode is on. Please turn off and try again." } else if (!ExponentNetwork.isNetworkAvailable(context)) { return "Can't connect to internet. Please try again." } } else if (exception is SocketTimeoutException) { return "Network response timed out." } return null } private fun isAirplaneModeOn(context: Context): Boolean { return Settings.System.getInt(context.contentResolver, Settings.Global.AIRPLANE_MODE_ON, 0) != 0 } }