Skip to content
/ except Public

A Go utility package that provides try-catch-finally exception handling mechanism for Go, inspired by traditional exception handling in languages like Java, Python, and JavaScript

License

Notifications You must be signed in to change notification settings

mew-sh/except

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Go Exception Handling Utility

Go Reference Go Report Card License: MIT

A Go utility package that provides try-catch-finally exception handling mechanism for Go, inspired by traditional exception handling in languages like Java, Python, and JavaScript.

Features

  • Try-Catch-Finally pattern implementation
  • Multiple exception types with predefined error types
  • Custom exception types support
  • Panic recovery - automatically catches and handles Go panics
  • Stack trace information for debugging
  • Nested exception handling support
  • Fluent API for chaining operations

Installation

go get github.com/mew-sh/except

Quick Start

package main

import (
    "fmt"
    "github.com/mew-sh/except"
)

func main() {
    e := except.New()
    e.Try(func() {
        data := getValue() // your function that might fail
        if data != 100 {
            e.Throw(e.AssertionError("Expected value is not the same as 100"))
        }
    }).
    Catch(e.In(e.AssertionErrorType, e.ValueErrorType), func(excep *except.Exception) {
        fmt.Println("Message:", excep.Message)
        fmt.Println("Exception Type:", excep.Type)
        fmt.Println("Here is the Stack Trace:", excep.StackTrace)
    }).
    Catch(nil, func(excep *except.Exception) {
        fmt.Println("I'll be executed as fallback:", excep.Message)
    }).
    Finally(func() {
        fmt.Println("I have been executing always to clean the world!")
    }).
    Run()
}

API Reference

Core Methods

except.New()

Creates a new exception handler instance.

Try(func())

Executes the provided function and captures any exceptions or panics.

Catch([]ExceptionType, func(*Exception))

Handles specific exception types. Pass nil as the first parameter for a catch-all handler.

Finally(func())

Executes cleanup code that runs regardless of whether an exception occurred.

Run()

Executes the try-catch-finally flow. Must be called at the end of the chain.

Throw(*Exception)

Throws an exception.

In(...ExceptionType)

Creates a list of exception types for matching in catch blocks.

Predefined Exception Types

The package provides the following predefined exception types:

  • AssertionErrorType - For assertion failures
  • IndexErrorType - For index out of bounds errors
  • RuntimeErrorType - For runtime errors
  • ValueErrorType - For invalid values
  • NetworkErrorType - For network-related errors
  • SyntaxErrorType - For syntax errors
  • PermissionErrorType - For permission-related errors
  • TimeoutErrorType - For timeout errors
  • TypeErrorType - For type-related errors
  • ConnectionErrorType - For connection errors
  • ReferenceErrorType - For reference errors
  • EOFErrorType - For end-of-file errors
  • LookupErrorType - For lookup/key not found errors
  • UnknownErrorType - For unknown errors

Exception Constructor Methods

Each exception type has a corresponding constructor method:

e := except.New()

// Create exceptions with optional custom messages
assertionErr := e.AssertionError("Custom assertion message")
indexErr := e.IndexError("Index out of bounds")
runtimeErr := e.RuntimeError("Runtime failure")
valueErr := e.ValueError("Invalid value provided")
networkErr := e.NetworkError("Network connection failed")
// ... and so on for all types

Custom Exception Types

You can create custom exception types:

const MyCustomErrorType except.ExceptionType = "MyCustomError"

e := except.New()
e.Try(func() {
    e.Throw(e.NewException(MyCustomErrorType, "This is a custom error"))
}).
Catch(e.In(MyCustomErrorType), func(excep *except.Exception) {
    fmt.Printf("Caught custom error: %s\n", excep.Message)
}).
Run()

Usage Examples

Basic Exception Handling

e := except.New()
e.Try(func() {
    // Code that might throw an exception
    if someCondition {
        e.Throw(e.ValueError("Invalid input"))
    }
}).
Catch(e.In(e.ValueErrorType), func(excep *except.Exception) {
    fmt.Printf("Value error: %s\n", excep.Message)
}).
Run()

Multiple Exception Types in One Catch Block

e := except.New()
e.Try(func() {
    // Code that might throw different types of exceptions
}).
Catch(e.In(e.NetworkErrorType, e.TimeoutErrorType, e.ConnectionErrorType), func(excep *except.Exception) {
    fmt.Printf("Network-related error: %s\n", excep.Message)
}).
Catch(e.In(e.ValueErrorType, e.TypeError), func(excep *except.Exception) {
    fmt.Printf("Data-related error: %s\n", excep.Message)
}).
Catch(nil, func(excep *except.Exception) {
    fmt.Printf("Fallback handler: %s\n", excep.Message)
}).
Run()

Panic Recovery

The package automatically recovers from Go panics:

e := except.New()
e.Try(func() {
    panic("Something went wrong!")
}).
Catch(nil, func(excep *except.Exception) {
    fmt.Printf("Caught panic: %s\n", excep.Message)
}).
Run()

Nested Exception Handling

e1 := except.New()
e1.Try(func() {
    e1.Throw(e1.NetworkError("Primary network failure"))
}).
Catch(e1.In(e1.NetworkErrorType), func(excep1 *except.Exception) {
    fmt.Printf("Primary error: %s\n", excep1.Message)
    
    // Handle recovery logic that might also fail
    e2 := except.New()
    e2.Try(func() {
        e2.Throw(e2.TimeoutError("Recovery attempt timed out"))
    }).
    Catch(e2.In(e2.TimeoutErrorType), func(excep2 *except.Exception) {
        fmt.Printf("Recovery error: %s\n", excep2.Message)
    }).
    Run()
}).
Finally(func() {
    fmt.Println("Cleanup completed")
}).
Run()

Finally Block for Cleanup

e := except.New()
e.Try(func() {
    // Code that might fail
}).
Catch(nil, func(excep *except.Exception) {
    // Handle any exception
}).
Finally(func() {
    // This always executes for cleanup
    fmt.Println("Cleaning up resources...")
}).
Run()

Exception Structure

The Exception struct contains the following fields:

type Exception struct {
    Message    string        // The error message
    Type       ExceptionType // The type of exception
    StackTrace string        // Stack trace information
}

Best Practices

  1. Always call Run() at the end of your exception handling chain
  2. Use specific exception types when possible instead of catch-all handlers
  3. Leverage the Finally block for cleanup operations
  4. Create custom exception types for domain-specific errors
  5. Use descriptive error messages when throwing exceptions

Testing

Run the tests to ensure everything works correctly:

go test -v

License

This project is open source and available under the MIT License.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

About

A Go utility package that provides try-catch-finally exception handling mechanism for Go, inspired by traditional exception handling in languages like Java, Python, and JavaScript

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages