Gestire le eccezioni in Go con exception

Mattepuffo's logo
Gestire le eccezioni in Go con exception

Gestire le eccezioni in Go con exception

Go di default non gestisce le eccezioni con il try/catch/finally, e non ne ha neanche bisogno.

Però per gli affezionati possiamo indicare exception!

In pratica non fa altro che aggiungere questa funzionalità.

Qui sotto il codice di esempio, funzionante, ripreso dalla documentazione ufficiale:

package main

import (
	"fmt"

	e "github.com/rbrahul/exception"
)

func main() {
	numero := 90

	e.Try(func() {
		if numero != 100 {
			e.Throw(e.AssertionError("Il valore deve essere 100"))
		}
	}).Catch(e.In(e.AssertionErrorType, e.ValueErrorType), func(excep *e.Exception) {
		fmt.Println("Messaggio:", excep.Message)
		fmt.Println("Tipo:", excep.Type)
		fmt.Println("Stack Trace:", excep.StackTrace)
	}).Catch(nil, func(excep *e.Exception) {
		fmt.Println("Fallback:", excep.Message)
	}).Finally(func() {
		fmt.Println("Operazione sempre eseguita!")
	}).Run()
}

Enjoy!


Condividi

Commentami!