ScriptForge.Exception serviço

O serviço Exception é um conjunto de métodos destinados a auxiliar na depuração de código em scripts Basic e Python e no tratamento de erros em scripts Basic.

Nos scripts Basic, quando ocorre um erro em tempo de execução, os métodos e propriedades do serviço Exception ajudam a identificar o contexto do erro e permitem tratá-lo.

Ícone da dica

Os erros e avisos gerados pelo serviço Exception são armazenados na memória e podem ser recuperados através do método Console.


A consola de serviço Exception armazena eventos, valores de variáveis e informações sobre erros. Utilize a consola quando não for fácil aceder ao IDE Básico, por exemplo, em funções definidas pelo utilizador (UDF) do Calc ou durante o processamento de eventos.

Utilize o método DebugPrint para adicionar qualquer informação relevante à consola. As entradas da consola podem ser exportadas para um ficheiro de texto ou visualizadas numa janela de diálogo.

Quando ocorre um erro, uma macro de aplicação pode:

  1. Comunique o erro na consola Exception

  2. Informar o utilizador sobre o erro, utilizando uma mensagem padrão ou uma mensagem personalizada

  3. Opcionalmente, interromper a sua execução

Quando é detetado um erro numa chamada à API do ScriptForge, o comportamento da aplicação é determinado por propriedades específicas:

  1. Registe o erro na consola Exception. Isto é feito sempre.

  2. Informe o utilizador sobre o erro através de uma mensagem padrão ou localizada.

    Para ativar o modo silencioso, defina:

    exception.ReportScriptErrors = False ' Default = True

  3. Para não interromper a execução da macro atual, defina:

    exception.StopWhenError = False ' Default = True


    Faz, então, sentido, antes de prosseguir com o processamento, analisar os valores de:

    exception.ReturnCode ' Short error description

    exception.ReturnCodeDescription ' Long error description

Nos scripts Python, o serviço Exception é utilizado principalmente para fins de depuração. Métodos como DebugPrint, Console e DebugDisplay são úteis para apresentar rapidamente mensagens, registar dados e abrir a janela da consola a partir de um script Python.

Ícone de nota

Nem todos os métodos e propriedades estão disponíveis para os scripts em Python, uma vez que a linguagem Python já dispõe de um sistema abrangente de gestão de exceções.


Chamada de serviço

Antes de utilizar o serviço Exception, é necessário carregar ou importar a biblioteca ScriptForge:

Ícone de nota

• As macros básicas requerem o carregamento da biblioteca ScriptForge através da seguinte instrução:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")

• Os scripts Python requerem a importação do módulo scriptforge:
from scriptforge import CreateScriptService


Em Basic

Os exemplos seguintes mostram três formas diferentes de chamar o método Raise. Todos os outros métodos podem ser executados de forma semelhante.


    SF_Exception.Raise(...)
  

    Dim exc : exc = SF_Exception
    exc.Raise(...)
  

    Dim exc : exc = CreateScriptService("Exception")
    exc.Raise(...)
  
Em Python

O trecho de código abaixo cria uma instância do serviço Exception, regista uma mensagem e apresenta a janela Console.


    from scriptforge import CreateScriptService
    exc = CreateScriptService("Exception")
    someVar = 100
    exc.DebugPrint("Value of someVar", someVar)
    exc.Console()
  

Propriedades

Ícone da dica

As propriedades abaixo indicadas estão disponíveis apenas para scripts Básicos. Estão relacionadas com erros que ocorrem em qualquer instrução de macro.


Nome

Readonly

Descrição

Description

Não

O texto da mensagem de erro.

O valor por predefinição é "" ou uma cadeia de caracteres que contenha a mensagem de erro de tempo de execução do Basic.

Number

Não

O código do erro. Pode ser um valor numérico ou texto.

O valor por predefinição é 0 ou o valor numérico correspondente ao código de erro de tempo de execução básico.

Source

Não

A localização no código onde ocorreu o erro. Pode ser um valor numérico ou texto.

O valor por predefinição é 0 ou o número da linha de código correspondente a um erro de tempo de execução padrão do Basic.


Ícone da dica

Raising or clearing an Exception resets its properties.


Ícone de nota

O intervalo de códigos de erro 0-2000 está reservado para o LibreOffice Basic. Os erros definidos pelo utilizador podem começar a partir de valores mais elevados, a fim de evitar conflitos com futuros desenvolvimentos do LibreOffice Basic.


Ícone da dica

The properties listed below are available for Basic and Python scripts. They are related to errors detected by the ScriptForge API only.


Name

Readonly

Return type

Description

ReportScriptErrors

No

Boolean

Indicates whether script errors are displayed in a message box when they occur.

Default value is False.

ReturnCode

Yes

String

The code returned by the last call to the ScriptForge API from a user script.

It is the zero-length string if everything ran without error.

ReturnCodeDescription

Yes

String

The description of the code returned by the last call to the ScriptForge API from a user script.

It is the zero-length string if everything ran without error.

StopWhenError

No

Boolean

Indicates whether the macro is stopped when ScriptForge detects a user script error.


List of Methods in the Exception Service

Clear
Console
ConsoleClear
ConsoleToFile

DebugDisplay
DebugPrint
PythonPrint

PythonShell
Raise
RaiseWarning


Clear

Resets the current error status and clears the SF_Exception properties.

Ícone de nota

Este método só está disponível para scripts Basic.


Sintaxe:


    SF_Exception.Clear()
  

Exemplo:

The following example shows how to catch a division-by-zero exception, whose error code is 11.


    Sub Example_Clear()
        Dim a, b, c
        On Local Error GoTo Catch
        Try:
            a = 10 : b = 0
            c = a / b
            '...
            Exit Sub
        Catch:
            If SF_Exception.Number = 11 Then SF_Exception.Clear()
            'If division by zero, ignore the error
    End Sub
  
Ícone da dica

For a complete list of Basic run-time error codes, refer to Debugging a Basic Program.


Console

Displays the console messages in a modal or non-modal dialog. In both modes, all the past messages issued by a DebugPrint() method or resulting from an exception are displayed. In non-modal mode, subsequent entries are added automatically.

If the console is already open, when non-modal, it is brought to the front.

A modal console can only be closed by the user. A non-modal console can either be closed by the user or upon macro termination.

Sintaxe:

exc.Console(modal: bool = True)

Parâmetros:

modal: Determine if the console window is modal (True) or non-modal (False). Default value is True.

Exemplo:

Em Basic

        SF_Exception.Console(Modal := False)
  
Em Python

    exc.Console(modal = False)
  

ConsoleClear

Clears the console keeping an optional number of recent messages. If the console is activated in non-modal mode, it is refreshed.

Sintaxe:

exc.ConsoleClear(keep: int = 0)

Parâmetros:

keep: The number of recent messages to be kept. Default value is 0.

Exemplo:

The following example clears the console keeping the 10 most recent messages.

Em Basic

        SF_Exception.ConsoleClear(10)
  
Em Python

    exc.ConsoleClear(10)
  

ConsoleToFile

Exports the contents of the console to a text file. If the file already exists and the console is not empty, it will be overwritten without warning. Returns True if successful.

Sintaxe:

exc.ConsoleToFile(filename: str): bool

Parâmetros:

filename: The name of the text file the console should be dumped into. The name is expressed according to the current FileNaming property of the SF_FileSystem service. By default, URL notation and the native operating system's format are both admitted.

Exemplo:

Em Basic

        SF_Exception.ConsoleToFile("C:\Documents\myFile.txt")
  
Em Python

    exc.ConsoleToFile(r"C:\Documents\myFile.txt")
  

DebugDisplay

Concatenates all the arguments into a single human-readable string and displays it in a MsgBox with an Information icon and an OK button.

The final string is also added to the Console.

Sintaxe:

exc.DebugDisplay(arg0: any, [arg1: any, ...])

Parâmetros:

arg0[, arg1, ...]: Any number of arguments of any type.

Exemplo:

Em Basic

    SF_Exception.DebugDisplay("Current Value", someVar)
  
Em Python

    exc.DebugDisplay("Current Value", someVar)
  

DebugPrint

Assembles all the given arguments into a single human-readable string and adds it as a new entry in the console.

Sintaxe:

exc.DebugPrint(arg0: any, [arg1: any, ...])

Parâmetros:

arg0[, arg1, ...]: Any number of arguments of any type.

Exemplo:

Em Basic

    SF_Exception.DebugPrint(Null, Array(1, 2, 3), "line1" & Chr(10) & "Line2", DateSerial(2020, 04, 09))
    ' [NULL]   [ARRAY] (0:2) (1, 2, 3)  line1\nLine2  2020-04-09
  
Em Python

    exc.DebugPrint(None, [1, 2, 3], "line1\nline2")
    # None  [1, 2, 3]  line1\nline2
  

PythonPrint

Displays the list of arguments in a readable form in the platform console. Arguments are separated by a TAB character (simulated by spaces).

The same string is added to the ScriptForge debug console.

If Python shell (APSO) is active, PythonPrint content is written to APSO console in place of the platform console.

Ícone de nota

Este método só está disponível para scripts Basic.


Sintaxe:


  exc.PythonPrint(arg0: any, [arg1: any, ...])
  

Parâmetros:

arg0[, arg1, ...]: Any number of arguments of any type. The maximum length of each individual argument is 1024 characters.

Exemplo:


    exc.PythonPrint(a, Array(1, 2, 3), , "line1" & Chr(10) & "Line2", DateSerial(2020, 04, 09))
  
Ícone de nota

In Python use a print statement to print to the APSO console or use the DebugPrint method to print to ScriptForge's console.


PythonShell

Opens an APSO Python shell as a non-modal window. The Python script keeps running after the shell is opened. The output from print statements inside the script are shown in the shell.

Only a single instance of the APSO Python shell can be opened at any time. Hence, if a Python shell is already open, then calling this method will have no effect.

Ícone de aviso

Este método requer a instalação da extensão APSO (Alternative Script Organizer for Python). Por sua vez, o APSO requer a presença do ambiente de scripts Python LibreOffice. Se o APSO ou o Python não estiverem instalados, ocorre um erro.


Sintaxe:

exc.PythonShell(opt variables: dict, background = 0xFDF6E3, foreground = 0x657B83)

Parâmetros:

variables: a Python dictionary with variable names and values that will be passed on to the APSO Python shell. By default all local variables are passed using Python's builtin locals() function.

background: Background color of the console specified as RGB 24 bits integer value. Default background is that of APSO.

foreground: Foreground color of the console specified as RGB 24 bits integer value. Default foreground is that of APSO.

Exemplo:

The example below opens the APSO Python shell passing all global and local variables considering the context where the script is running. Console is displayed with white characters on a black background.


    exc.PythonShell({**globals(), **locals()}, \
        background = 0x0, foreground = 0xFFFFFF)
  

When the APSO Python shell is open, any subsequent output printed by the script will be shown in the shell. Hence, the string printed in the example below will be displayed in the Python shell.


    s = CreateScriptService('Basic')
    RED, BLUE = s.RGB(255,0,0), s.RGB(0,0,255)
    exc.PythonShell(background=RED, foreground=BLUE)
    print("Hello world!")
  

Raise

Generates a run-time error. An error message is displayed to the user and reported in the console. The execution is stopped. The Raise() method can be placed inside the normal script flow or in a dedicated error-handling routine.

Ícone de nota

Este método só está disponível para scripts Basic.


Sintaxe:


    SF_Exception.Raise(Number := Err, [Source := Erl], [Description := Error$])
  

The code snippets presented next are equivalent. They show alternative ways to raise an exception with code 2100.


    SF_Exception.Raise(2100)
  

    SF_Exception.Number = 2100
    SF_Exception.Raise()
  

    SF_Exception.Raise Number := 2100
  

Parâmetros:

Number: The error code, as a number or as a string. Default value is that of Err Basic builtin function, in which case Number is optional.

Ícone de nota

O intervalo de códigos de erro 0-2000 está reservado para o LibreOffice Basic. Os erros definidos pelo utilizador podem começar a partir de valores mais elevados, a fim de evitar conflitos com futuros desenvolvimentos do LibreOffice Basic.


Source: The location of the error, as a number or as a string. Default value is that of Erl Basic builtin function.

Description: The message to display to the user and to report in the console. Default value is that of Error$ Basic builtin function.

Exemplo:


    Sub Example_Raise()
        Dim a, b, c
        On Local Error GoTo Catch
        Try:
            a = 10 : b = 0
            c = a / b
            '...
            Exit Sub
        Catch:
            'See variants below ...
    End Sub
  

To raise an exception with the standard values:


    Catch:
        SF_Exception.Raise()
  

To raise an exception with a specific code:


    Catch:
        SF_Exception.Raise(11)
  

To replace the usual message:


    Catch:
        SF_Exception.Raise(, , "It is not a good idea to divide by zero.")
  

To raise an application error:


    Catch:
        SF_Exception.Raise("MyAppError", "Example_Raise()", "Something wrong happened !")
  

RaiseWarning

This method has exactly the same syntax, arguments and behavior as the Raise() method.

However, when a warning is raised, the macro execution is not stopped.

Ícone de nota

Este método só está disponível para scripts Basic.


Sintaxe:


    SF_Exception.RaiseWarning([Number As Variant], [Source As Variant], [Description As String])
  

Parâmetros:

Number: The error code, as a number or as a string. Default value is that of Err Basic builtin function, in which case Number is optional.

Ícone de nota

O intervalo de códigos de erro 0-2000 está reservado para o LibreOffice Basic. Os erros definidos pelo utilizador podem começar a partir de valores mais elevados, a fim de evitar conflitos com futuros desenvolvimentos do LibreOffice Basic.


Source: The location of the error, as a number or as a string. Default value is that of Erl Basic builtin function.

Description: The message to display to the user and to report in the console. Default value is that of Error$ Basic builtin function.

Exemplo:


    SF_Exception.RaiseWarning(Source:="Example_Raise()", _
        Description:="Something wrong happened !", _
        Number:="MyAppError")
  
Necessitamos da sua ajuda!

Necessitamos da sua ajuda!