B4J Code Snippet Convert Exception Stack Trace To String

Discussion in 'B4J Code Snippets' started by keirS, Apr 28, 2019.

  1. keirS

    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.


    Code:
    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 StringAs Boolean
        
    Return True
    End Sub
    Sub ExceptionToString(E As ExceptionAs 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
     
    Erel likes this.
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice