Gestione degli errori in Azure Databricks

Si applica a:segno di spunta sì Databricks SQL segno di spunta sì Databricks Runtime 12.2 e versioni successive

Componenti di errore

Quando Azure Databricks genera un errore, include i componenti seguenti:

  • Classe Error

    Stringa descrittiva, leggibile e leggibile, univoca per la condizione di errore.

    Alcune classi di errore includono sottolasse.

    Ad esempio: "TABLE_OR_VIEW_NOT_FOUND" e "INCOMPLETE_TYPE_DEFINITION". MATRICE'.

    Per un elenco di tutte le classi di errore, vedere Classi di errore.

  • SQLSTATE

    Stringa lunga cinque caratteri, raggruppamento di classi di errore in un formato standard supportato da molti prodotti e API.

    Ad esempio: '42P01'

    Per un elenco completo di tutti i SQLSTATEdati usati da Azure Databricks, vedere SQLSTATEs.

  • Messaggio con parametri

    Messaggio di errore con segnaposto per i parametri.

    Ad esempio: 'TABLE_OR_VIEW_NOT_FOUND' include il messaggio seguente:

    The table or view <relationName> cannot be found.
    

    È possibile usare il messaggio con parametri per eseguire il rendering di un messaggio di errore eseguendo il mapping dei valori dei parametri del messaggio ai tag <parameter>del parametro .

  • Parametri del messaggio

    Mappa di parametri e valori che forniscono informazioni aggiuntive sull'errore. Ad esempio: 'relationName' -> 'main.default.tab1'.

  • Messaggio

    Messaggio di errore di cui è stato eseguito il rendering completo, inclusa la classe di errore e SQLSTATE, con i parametri compilati. Ad esempio:

    [TABLE_OR_VIEW_NOT_FOUND] The table or view `does_not_exist` cannot be found. Verify the spelling and correctness of the schema and catalog.
    If you did not qualify the name with a schema, verify the current_schema() output, or qualify the name with the correct schema and catalog.
    To tolerate the error on drop use DROP VIEW IF EXISTS or DROP TABLE IF EXISTS. SQLSTATE: 42P01; line 1 pos 14;
    'Project [*]
    +- 'UnresolvedRelation [does_not_exist], [], false
    

Avviso

Il messaggio e il messaggio con parametri non sono stabili tra le versioni. Il testo del messaggio può essere modificato o localizzato senza preavviso. Per gestire a livello di codice una condizione di errore, usare invece i parametri Error Class, SQLSTATEe Message.

Gestione delle condizioni di errore

Si applica a: segno di spunta sì Databricks SQL segno di spunta sì Databricks Runtime 14.2 e versioni successive

Importante

Questa funzionalità è disponibile in anteprima pubblica.

Azure Databricks fornisce API specifiche del linguaggio per gestire le condizioni di errore.

Python

Per Python usare pySparkException

  • PySparkException.getErrorClass(): restituisce la classe di errore dell'eccezione come stringa.
  • PySparkException.getMessageParameters(): restituisce i parametri del messaggio dell'eccezione come dizionario.
  • PySparkException.getSqlState(): restituisce l'oggetto SQLSTATE dell'espressione come stringa.

Scala

Per Scala usare SparkThrowable

  • getErrorClass(): restituisce una classe di errore come stringa.
  • getMessageParameters(): restituisce i parametri di un messaggio come mappa.
  • getSqlState(): restituisce un'istruzione SQLSTATE come stringa.

Esempi

  • Intercettare eventuali eccezioni e visualizzare la classe di errore, i parametri del messaggio e SQLSTATE. Visualizzare anche il messaggio di errore predefinito

    Scala

    import org.apache.spark.SparkThrowable
    
    try {
      spark.sql("SELECT * FROM does_not_exist").show()
    }
    catch {
      case ex: SparkThrowable =>
        println("Error Class       : " + ex.getErrorClass)
        println("Message parameters: " + ex.getMessageParameters())
        println("SQLSTATE          : " + ex.getSqlState)
        println(ex)
    }
    

    Python

    from pyspark.errors import PySparkException
    
    try:
      spark.sql("SELECT * FROM does_not_exist").show()
    except PySparkException as ex:
      print("Error Class       : " + ex.getErrorClass())
      print("Message parameters: " + str(ex.getMessageParameters()))
      print("SQLSTATE          : " + ex.getSqlState())
      print(ex)
    

    Risultato

      Error Class       : TABLE_OR_VIEW_NOT_FOUND
      Message parameters: {'relationName': '`does_not_exist`'}
      SQLSTATE          : 42P01
      [TABLE_OR_VIEW_NOT_FOUND] The table or view `does_not_exist` cannot be found. Verify the spelling and correctness of the schema and catalog.
      If you did not qualify the name with a schema, verify the current_schema() output, or qualify the name with the correct schema and catalog.
      To tolerate the error on drop use DROP VIEW IF EXISTS or DROP TABLE IF EXISTS. SQLSTATE: 42P01; line 1 pos 14;
      'Project [*]
      +- 'UnresolvedRelation [does_not_exist], [], false
    
  • Intercettare solo SQLSTATE 42P01 e visualizzare un messaggio personalizzato:

    Scala

    import org.apache.spark.SparkThrowable
    
    try {
      spark.sql("SELECT * FROM does_not_exist").show()
    }
    catch {
      case ex: SparkThrowable if (ex.getSqlState == "42P01") =>
        println("I'm so sorry, but I cannot find: " + ex.getMessageParameters().get("relationName"))
    }
    

    Python

    from pyspark.errors import PySparkException
    
    try:
      spark.sql("SELECT * FROM does_not_exist").show()
    except PySparkException as ex:
      if (ex.getSqlState() == "42P01"):
        print("I'm so sorry, but I cannot find: " + ex.getMessageParameters()['relationName'])
      else:
        raise
    

    Risultato

    I'm so sorry, but I cannot find: `does_not_exist`
    
  • Intercettare solo la classe TABLE_OR_VIEW_NOT_FOUND di errore e visualizzare un messaggio personalizzato:

    Scala

    import org.apache.spark.SparkThrowable
    
    try {
      spark.sql("SELECT * FROM does_not_exist").show()
    }
    catch {
      case ex: SparkThrowable if (ex.getErrorClass == "TABLE_OR_VIEW_NOT_FOUND") =>
        println("I'm so sorry, but I cannot find: " + ex.getMessageParameters().get("relationName"))
    }
    

    Python

    from pyspark.errors import PySparkException
    
    try:
      spark.sql("SELECT * FROM does_not_exist").show()
    except PySparkException as ex:
      if (ex.getErrorClass() == "TABLE_OR_VIEW_NOT_FOUND"):
        print("I'm so sorry, but I cannot find: " + ex.getMessageParameters()['relationName'])
      else:
        raise
    

    Risultato

    I'm so sorry, but I cannot find: `does_not_exist`
    

Eccezioni generate dall'utente

Azure Databricks offre le funzioni seguenti per generare errori definiti dall'utente:

  • raise_error

    Genera un'eccezione con un messaggio di errore personalizzato.

  • assert_true

    Genera un errore con un messaggio di errore facoltativo, se non viene soddisfatta una condizione.

Entrambe le funzioni restituiscono la classe di errore 'U edizione Standard R_RAI edizione Standard D_EXCEPTION' e insieme a SQLSTATE'P0001' un messaggio definito dall'utente.

Esempi

> SELECT raise_error('This is a custom error message');
 [USER_RAISED_EXCEPTION] This is a custom error message. SQLSTATE: P0001

> SELECT assert_true(1 = 2, 'One is not two!');
 [USER_RAISED_EXCEPTION] One is not two! SQLSTATE: P0001

> SELECT assert_true(1 = 2);
 [USER_RAISED_EXCEPTION] '(1 = 2)' is not true! SQLSTATE: P0001