Thanks to visit codestin.com
Credit goes to pkg.go.dev

api

package module
v0.0.0-...-f2e74c8 Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2024 License: MIT Imports: 3 Imported by: 8

README

Standardized API Error Handling for Go

Go Reference Go Report Card Code Coverage

This library provides a set of common error definitions used across various API interactions. By using this library, you can achieve consistent error handling in your applications, making it easier to debug, maintain, and integrate with different services.

It is utilized by all API libraries within the go-api-libs organization.

Features

  • Wrap Errors: Easily wrap underlying errors with API-specific errors to provide more context.
  • Error Identification: Check and identify the nature of errors using Go's errors.Is and errors.As functions.
  • Custom Errors: Define and use custom errors specific to your API needs.
  • Status Code Handling: Handle and identify errors based on HTTP status codes.
  • Content Type Handling: Handle errors based on content type mismatches.

Installation

To install the library, run:

go get github.com/go-api-libs/api

Usage

Here is a basic example of how to use the api library for error handling:

package main

import (
	"context"
	"errors"
	"fmt"
	"os"
	"time"

	"github.com/go-api-libs/api"
	"github.com/go-api-libs/toggl/pkg/toggl"
)

func main() {
	c, err := toggl.NewClientWithAPIToken(os.Getenv("TOGGL_TOKEN"))
	if err != nil {
		panic(err)
	}

	ctx := context.Background()
	now := time.Now()
	entries, err := c.ListTimeEntriesInRange(ctx, now.Add(-24*time.Hour), now)
	if err != nil {
		decErr := &api.DecodingError{}
		if errors.As(err, &decErr) {
			fmt.Println("Could not decode response:", decErr.Err)
		}

		apiErr := &api.Error{}
		if errors.As(err, &apiErr) {
			fmt.Println("Response Status Code:", apiErr.StatusCode())
			fmt.Println("Response Content Type:", apiErr.ContentType())
			if apiErr.IsCustom {
				fmt.Println("API sent back the error:", apiErr.Err)
				return
			}
		}

		if errors.Is(err, api.ErrStatusCode) {
			fmt.Println("The response status code indicates an error (but is properly documented).")
			// NOTE: Some APIs have custom error responses that don't contain api.ErrStatusCode.
			// If the status code indicates an error and the API returns a JSON,
			// we unmarshal it and return it as an object that fulfils the error interface.
			// If this happens, `IsCustom` above is set to true.
		} else if errors.Is(err, api.ErrUnknownStatusCode) {
			fmt.Println("The returned status code is not documented in the API specification.")
		}

		if errors.Is(err, api.ErrUnknownContentType) {
			fmt.Println("The response content type is not documented in the API specification.")
		}

		panic(err)
	}

	// Use entries slice
}

Contributing

If you have any contributions to make, please submit a pull request or open an issue on the GitHub repository.

License

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

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnknownStatusCode is returned when the response status code is not known,
	// i.e. it has not been defined in the OpenAPI specification.
	ErrUnknownStatusCode = errors.New("unknown status code")
	// ErrUnknownContentType is returned when the response content type is not known,
	// i.e. it has not been defined in the OpenAPI specification
	// for the status code of the response.
	ErrUnknownContentType = errors.New("unknown content type")
	// ErrStatusCode is returned when the status code indicates an error.
	ErrStatusCode = errors.New("status code indicates an error")
)

Functions

func NewErrCustom

func NewErrCustom(rsp *http.Response, err error) error

NewErrCustom wraps a custom error in an api.Error. Use this if the status code is unsuccessful and the API returns more information, e.g. as part of a JSON that can be parsed and transformed into an error.

func NewErrStatusCode

func NewErrStatusCode(rsp *http.Response) error

func NewErrUnknownContentType

func NewErrUnknownContentType(rsp *http.Response) error

func NewErrUnknownStatusCode

func NewErrUnknownStatusCode(rsp *http.Response) error

func WrapDecodingError

func WrapDecodingError(rsp *http.Response, err error) error

WrapDecodingError wraps the error in a DecodingError, which is then wrapped into an api.Error containing the response. Use errors.As to check if the error returned by an API library is a DecodingError.

Types

type DecodingError

type DecodingError struct{ Err error }

DecodingError is an error returned when decoding the response body failed.

func (DecodingError) Error

func (d DecodingError) Error() string

Error returns the error message.

func (*DecodingError) Unwrap

func (e *DecodingError) Unwrap() error

Unwrap returns the underlying error, e.g. a json.SemanticError.

type Error

type Error struct {
	// The HTTP response.
	Response *http.Response
	// The underlying error.
	Err error
	// Indicates that this is a custom error returned by the API.
	IsCustom bool
}

Error is an error returned by the API client. Use errors.As to check if the underlying error is of a specific type.

func (Error) ContentType

func (e Error) ContentType() string

ContentType returns the HTTP content type.

func (*Error) Error

func (e *Error) Error() string

Error returns the error message.

func (Error) StatusCode

func (e Error) StatusCode() int

StatusCode returns the HTTP status code of the response.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying error.

Jump to

Keyboard shortcuts

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