B4J Code Snippet Convert Exception Stack Trace To String

keirS

Well-Known Member
Licensed User
I want to give users a chance to send application crashes to be logged on a website so I need to capture the stack trace to a string. The ExceptionToString Sub does that.


B4X:
Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
End Sub
Sub AppStart (Form1 As Form, Args() As String)
    Dim A = 1
    Dim B = 0
    Dim m As Map
    MainForm = Form1
    'MainForm.RootPane.LoadLayout("Layout1") 'Load the layout file.
    MainForm.Show
    Try
       'Cause A Crash!
       m.Put("ABC",1234)
    Catch
        Log(ExceptionToString(LastException))
    End Try
End Sub
'Return true to allow the default exceptions handler to handle the uncaught exception.
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
    Return True
End Sub
Sub ExceptionToString(E As Exception) As String
    Dim JOByteArrayInputStream As JavaObject
    Dim JOPrintStream As JavaObject
    Dim JOCharSet As JavaObject
    Dim JOException As JavaObject = E
    JOByteArrayInputStream.InitializeNewInstance("java.io.ByteArrayOutputStream",Null)
    JOPrintStream.InitializeNewInstance("java.io.PrintStream",Array(JOByteArrayInputStream,True,"UTF-8"))
    JOException.RunMethod("printStackTrace",Array(JOPrintStream))
    Return JOByteArrayInputStream.RunMethod("toString",Array("UTF-8"))
  
End Sub
 
Top