except

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2025 License: MIT Imports: 4 Imported by: 0

README

Go Exception Handling Utility

Go Reference Go Report Card

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.

Documentation

Overview

Package except provides try-catch-finally exception handling for Go.

This package implements a traditional exception handling mechanism inspired by languages like Java, Python, and JavaScript, allowing developers to use familiar try-catch-finally patterns in Go.

Copyright (c) 2025 mew-sh Licensed under the MIT License. See LICENSE file for details.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Exception

type Exception struct {
	Message    string
	Type       ExceptionType
	StackTrace string
}

Exception represents an exception with message, type and stack trace

type ExceptionHandler

type ExceptionHandler struct {

	// Export exception types for easy access
	AssertionErrorType  ExceptionType
	IndexErrorType      ExceptionType
	RuntimeErrorType    ExceptionType
	ValueErrorType      ExceptionType
	NetworkErrorType    ExceptionType
	SyntaxErrorType     ExceptionType
	PermissionErrorType ExceptionType
	TimeoutErrorType    ExceptionType
	TypeErrorType       ExceptionType
	ConnectionErrorType ExceptionType
	ReferenceErrorType  ExceptionType
	EOFErrorType        ExceptionType
	LookupErrorType     ExceptionType
	UnknownErrorType    ExceptionType
	// contains filtered or unexported fields
}

ExceptionHandler is the main handler for try-catch-finally operations

func New

func New() *ExceptionHandler

New creates a new exception handler instance

func (*ExceptionHandler) AssertionError

func (e *ExceptionHandler) AssertionError(args ...interface{}) *Exception

AssertionError creates an assertion error exception

func (*ExceptionHandler) Catch

func (e *ExceptionHandler) Catch(exceptionTypes []ExceptionType, cb func(excep *Exception)) *ExceptionHandler

Catch handles exceptions based on the provided exception types

func (*ExceptionHandler) ConnectionError

func (e *ExceptionHandler) ConnectionError(args ...interface{}) *Exception

ConnectionError creates a connection error exception

func (*ExceptionHandler) EOFError

func (e *ExceptionHandler) EOFError(args ...interface{}) *Exception

EOFError creates an EOF error exception

func (*ExceptionHandler) Finally

func (e *ExceptionHandler) Finally(cb func()) *ExceptionHandler

Finally executes the provided function regardless of whether an exception occurred

func (*ExceptionHandler) In

func (e *ExceptionHandler) In(exceptionTypes ...ExceptionType) []ExceptionType

In creates a list of exception types for matching in catch blocks

func (*ExceptionHandler) IndexError

func (e *ExceptionHandler) IndexError(args ...interface{}) *Exception

IndexError creates an index error exception

func (*ExceptionHandler) LookupError

func (e *ExceptionHandler) LookupError(args ...interface{}) *Exception

LookupError creates a lookup error exception

func (*ExceptionHandler) NetworkError

func (e *ExceptionHandler) NetworkError(args ...interface{}) *Exception

NetworkError creates a network error exception

func (*ExceptionHandler) NewException

func (e *ExceptionHandler) NewException(exceptionType ExceptionType, args ...interface{}) *Exception

NewException creates a new Exception with the specified type and optional message

func (*ExceptionHandler) PermissionError

func (e *ExceptionHandler) PermissionError(args ...interface{}) *Exception

PermissionError creates a permission error exception

func (*ExceptionHandler) ReferenceError

func (e *ExceptionHandler) ReferenceError(args ...interface{}) *Exception

ReferenceError creates a reference error exception

func (*ExceptionHandler) Run

func (e *ExceptionHandler) Run()

Run executes the try-catch-finally flow

func (*ExceptionHandler) RuntimeError

func (e *ExceptionHandler) RuntimeError(args ...interface{}) *Exception

RuntimeError creates a runtime error exception

func (*ExceptionHandler) SyntaxError

func (e *ExceptionHandler) SyntaxError(args ...interface{}) *Exception

SyntaxError creates a syntax error exception

func (*ExceptionHandler) Throw

func (e *ExceptionHandler) Throw(exp *Exception)

Throw throws an exception

func (*ExceptionHandler) TimeoutError

func (e *ExceptionHandler) TimeoutError(args ...interface{}) *Exception

TimeoutError creates a timeout error exception

func (*ExceptionHandler) Try

func (e *ExceptionHandler) Try(cb func()) *ExceptionHandler

Try executes the provided function and captures any panics or exceptions

func (*ExceptionHandler) TypeError

func (e *ExceptionHandler) TypeError(args ...interface{}) *Exception

TypeError creates a type error exception

func (*ExceptionHandler) UnknownError

func (e *ExceptionHandler) UnknownError(args ...interface{}) *Exception

UnknownError creates an unknown error exception

func (*ExceptionHandler) ValueError

func (e *ExceptionHandler) ValueError(args ...interface{}) *Exception

ValueError creates a value error exception

type ExceptionType

type ExceptionType string

ExceptionType represents the type of exception

const (
	UnknownErrorType    ExceptionType = "UnknownError"
	IndexErrorType      ExceptionType = "IndexError"
	RuntimeErrorType    ExceptionType = "RuntimeError"
	ValueErrorType      ExceptionType = "ValueError"
	NetworkErrorType    ExceptionType = "NetworkError"
	SyntaxErrorType     ExceptionType = "SyntaxError"
	PermissionErrorType ExceptionType = "PermissionError"
	TimeoutErrorType    ExceptionType = "TimeoutError"
	TypeErrorType       ExceptionType = "TypeError"
	AssertionErrorType  ExceptionType = "AssertionError"
	ConnectionErrorType ExceptionType = "ConnectionError"
	ReferenceErrorType  ExceptionType = "ReferenceError"
	EOFErrorType        ExceptionType = "EOFError"
	LookupErrorType     ExceptionType = "LookupError"
)

Predefined exception types

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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