nerror

package module
v1.1.3 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2025 License: MIT Imports: 2 Imported by: 11

README

Go Report Card GoDoc

neji

neji is a lightweight Go package for generating structured JSON error responses and handling parameter validation errors. It provides utility functions to standardize error handling in API applications.

Features

  • 🔧 Structured JSON Error Responses: Generate consistent error responses in two formats
  • Parameter Validation: Standardized missing parameter error messages
  • 🔗 Error Wrapping: Preserve original errors while adding context
  • 🧪 Well Tested: Comprehensive test coverage with edge cases
  • 📦 Zero Dependencies: Only standard library (except for tests)

Installing

go get -u github.com/junkd0g/neji

✅ Running Tests

go test ./...

🚀 Usage

Basic Error Response
package main

import (
	"errors"
	"net/http"

	"github.com/gorilla/mux"
	nerror "github.com/junkd0g/neji"
)

func HelloWorld(w http.ResponseWriter, r *http.Request) {
	err := errors.New("This is the best error message ever")
	errorResponse, _ := nerror.SimpleErrorResponseWithStatus(500, err)

	w.Header().Set("Content-Type", "application/json")
	w.Write(errorResponse)
}

func main() {
	router := mux.NewRouter().StrictSlash(true)
	router.HandleFunc("/", HelloWorld)
	http.ListenAndServe(":8076", router)
}
API Reference
SimpleErrorResponseWithStatus
nerror.SimpleErrorResponseWithStatus(500, err)

Returns:

{
	"message": "Your json is wrong or something",
	"status": 500
}
SimpleErrorResponseWithCodeV2
nerror.SimpleErrorResponseWithCodeV2(500, err)

Returns:

{
	"error": {
		"status": 500,
		"message": "Your json is wrong or something"
	}
}
Parameter Validation
// Generate standardized parameter error
err := nerror.ErrInvalidParameter("user_id")
// Returns: "missing parameter user_id"
Error Wrapping
// Wrap errors with additional context
originalErr := errors.New("connection timeout")
wrappedErr := nerror.WrapError(originalErr, "failed to fetch data")
// Returns: "failed to fetch data: connection timeout"

📝 License

This project is licensed under the MIT License. See the LICENSE file for details.

Authors

Documentation

Overview

Package nerror provides utility functions and structures for handling structured JSON error responses in API applications.

It defines error response formats commonly used in APIs, including simple error messages and nested error structures. The package also offers helper functions for serializing error messages into JSON format.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ErrInvalidParameter

func ErrInvalidParameter(message string) error

ErrInvalidParameter returns an error indicating a missing or invalid parameter.

This function helps standardize parameter validation errors by formatting a descriptive message with the provided parameter name.

Example usage:

err := ErrInvalidParameter("user_id")
fmt.Println(err) // Output: "missing parameter user_id"

@param message The name of the missing or invalid parameter. @return Formatted error message.

func SimpleErrorResponseWithCodeV2

func SimpleErrorResponseWithCodeV2(status int, err error) ([]byte, error)

SimpleErrorResponseWithCodeV2 creates a JSON-formatted error response using the SimpleErrorMessageV2 structure.

It returns a JSON response in the format:

{
    "error": {
        "status": 502,
        "message": "Bad gateway."
    }
}

@param status HTTP status code. @param err The error message. @return JSON-encoded error response as []byte and any marshaling error.

func SimpleErrorResponseWithStatus

func SimpleErrorResponseWithStatus(status int, err error) ([]byte, error)

SimpleErrorResponseWithStatus creates a JSON-formatted error response using the SimpleErrorMessage structure.

It returns a JSON response in the format:

{
    "message": "Your JSON is wrong or something",
    "status": 500
}

@param status HTTP status code. @param err The error message. @return JSON-encoded error response as []byte and any marshaling error.

func WrapError

func WrapError(err error, message string) error

WrapError wraps an existing error with additional context, preserving the original error.

This function is useful for adding meaningful context to errors before propagating them, aiding in debugging and error analysis.

Example usage:

err := errors.New("connection timeout")
wrappedErr := WrapError(err, "failed to fetch data")
fmt.Println(wrappedErr) // Output: "failed to fetch data: connection timeout"

@param err The original error to wrap. @param message Additional context message to include. @return Wrapped error message.

Types

type SimpleErrorMessage

type SimpleErrorMessage struct {
	Message string `json:"message"`
	Status  int    `json:"status"`
}

SimpleErrorMessage represents a basic JSON error response format.

Example JSON output:

{
    "message": "Your JSON is wrong or something",
    "status": 500
}

type SimpleErrorMessageV2

type SimpleErrorMessageV2 struct {
	ErrorST SimpleErrorMessage `json:"error"`
}

SimpleErrorMessageV2 represents a more structured JSON error response format, encapsulating the error message within an "error" object.

Example JSON output:

{
    "error": {
        "status": 502,
        "message": "Bad gateway."
    }
}

Jump to

Keyboard shortcuts

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