try

package
v1.17.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 2, 2025 License: MIT Imports: 0 Imported by: 5

README

Try-Finally-Catch

A Go package that provides structured error handling similar to try-catch-finally blocks in other languages, but adapted for Go's panic/recover mechanism.

Overview

The try package offers a clean and structured way to handle errors and panics in Go code. It allows you to:

  • Execute code that might panic in a controlled environment
  • Ensure cleanup code always runs, even if an error occurs
  • Handle errors in a structured way
  • Rethrow or transform errors as needed

Installation

go get github.com/gflydev/core

Usage

Basic Example
package main

import (
    "github.com/gflydev/core/try"
    "log"
)

func main() {
    try.Perform(func() {
        // Code that might panic
        result := riskyOperation()
        processResult(result)
    }).Finally(func() {
        // Cleanup code that always runs
        cleanup()
    }).Catch(func(e try.E) {
        // Error handling code
        log.Printf("Error occurred: %v", e)
    })
}
Error Handling Patterns
Simple Error Handling
package example

import (
    "github.com/gflydev/core/try"
    "log"
)

func example() {
    try.Perform(func() {
        if err := someOperation(); err != nil {
            panic(err)
        }
    }).Catch(func(e try.E) {
        log.Printf("Operation failed: %v", e)
    })
}
Using Throw for Custom Errors
package example

import (
    "github.com/gflydev/core/try"
    "log"
)

func example() {
    try.Perform(func() {
        if value < 0 {
            try.Throw("Value cannot be negative")
        }
    }).Catch(func(e try.E) {
        log.Printf("Validation error: %v", e)
    })
}
Rethrowing Errors
package example

import (
    "github.com/gflydev/core/try"
    "log"
)

func example() {
    try.Perform(func() {
        // Some code that might panic
    }).Catch(func(e try.E) {
        log.Printf("Error occurred: %v", e)

        // Rethrow the original error
        try.Throw(nil)
    })
}
Resource Management
package example

import (
    "github.com/gflydev/core/try"
    "log"
    "os"
)

func example() {
    var file *os.File

    try.Perform(func() {
        var err error
        file, err = os.Open("example.txt")
        if err != nil {
            panic(err)
        }

        // Process the file
        processFile(file)
    }).Finally(func() {
        // Close the file if it was opened
        if file != nil {
            file.Close()
        }
    }).Catch(func(e try.E) {
        log.Printf("File operation failed: %v", e)
    })
}

Best Practices

  1. Keep Try Blocks Focused: Each try block should focus on a specific operation that might fail.

  2. Always Use Finally for Cleanup: Use Finally for any cleanup operations that should always run, regardless of whether an error occurred.

  3. Be Specific in Catch Blocks: Handle specific error types when possible, rather than catching all errors.

  4. Avoid Nested Try Blocks: Instead of nesting try blocks, chain them sequentially for better readability.

  5. Don't Overuse: While this package provides a convenient way to handle errors, it's not a replacement for Go's standard error handling. Use it for complex error handling scenarios where the structured approach adds clarity.

API Reference

Functions
  • Perform(func()): Starts a try-catch-finally block by executing the provided function.
  • Throw(error): Explicitly throws a panic that can be caught by a catch block.
Methods
  • Finally(func()): Registers a function to be executed at the end of the try-catch block.
  • Catch(func(error)): Registers an error-handling function that is executed if an error occurs.

License

This package is part of the gFlyDev Core library and is licensed under the same terms.

Documentation

Index

Constants

View Source
const RethrowPanic = "___throw_it___"

RethrowPanic is a special marker used to indicate that the original panic should be rethrown. This is used internally by the Throw function when called with nil.

Variables

This section is empty.

Functions

func Throw

func Throw(e E)

Throw explicitly throws a panic that can be caught by a catch block. This is useful for rethrowing errors or creating custom errors.

Parameters:

  • e: The error to be thrown. If nil, the original panic value will be rethrown.

Behavior:

  • If e is nil, a special RethrowPanic marker is used to indicate the original error should be used.
  • Otherwise, the provided value is directly used as the panic value.

Example:

Perform(func() {
    if err := someOperation(); err != nil {
        Throw(err) // Throw a specific error
    }
}).Catch(func(e E) {
    // Handle the error
})

Types

type E

type E any

E represents any type of error or panic value. This is an alias for any to allow catching any type of panic.

type EF

type EF func(err E)

EF represents a function that takes an error parameter. Used for catch blocks to handle errors.

type F

type F func()

F represents a function with no parameters and no return value. Used for try and finally blocks.

type It

type It struct {
	Error E // The error/panic value if one occurred
	// contains filtered or unexported fields
}

It is the main structure that chains try, finally, and catch blocks. It holds the state of the error handling process.

func Perform

func Perform(funcToTry F) (o *It)

Perform starts a try-catch-finally block by executing the provided function. This is the entry point for the error handling pattern.

Parameters:

  • funcToTry: The main logic to execute within the try block.

Returns:

  • *It: An instance of the It structure for chaining Finally and Catch calls.

Example:

Perform(func() {
    // Code that might panic
}).Finally(func() {
    // Cleanup code that always runs
}).Catch(func(e E) {
    // Error handling code
})

func (*It) Catch

func (o *It) Catch(funcCaught EF) *It

Catch registers an error-handling function that is executed if an error occurs in the try block. If no error occurred, the catch block is skipped.

Parameters:

  • funcCaught: The function to handle the error, which receives the error as a parameter.

Returns:

  • *It: The same instance of It structures for chaining.

Behavior:

  • If an error occurred in the try block, the catch function is executed with the error.
  • If no error occurred, the catch function is skipped.
  • The final function (if registered) is always executed, even if the catch block panics.
  • If the catch block panics, the panic is propagated after the finally block executes.
  • If Throw(nil) is called in the catch block, the original error is rethrown.

Example:

Perform(func() {
    // Code that might panic
}).Catch(func(e E) {
    // Handle the error
    log.Printf("Error: %v", e)
})

func (*It) Finally

func (o *It) Finally(finallyFunc F) *It

Finally registers a function to be executed at the end of the try-catch block, regardless of whether an error occurred or not.

Parameters:

  • finallyFunc: The function containing cleanup or finalization logic.

Returns:

  • *It: The same instance of It structure for chaining.

Panics:

  • If Finally is called more than once on the same It instance.

Example:

Perform(func() {
    // Open a file
}).Finally(func() {
    // Close the file, regardless of errors
}).Catch(func(e E) {
    // Handle any errors
})

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL