api

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

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 5 Imported by: 12 modules, 8 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Go Reference Code Coverage License

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.

For the code openapi-codegen generates, it also holds:

  • union: decoding and encoding unions and tagged structs.
  • apitest: replaying recorded interactions in generated tests.
  • paging: paging.Pages and paging.Items yield what an API lists a page at a time, fetching each page as the one before is used up, and stopping when the loop breaks or at the first error.

Usage

To install the library, run:

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

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
}

Additional Information

Contributing

Contributions are welcome — please open an issue or a pull request on GitHub.

License

This project is licensed under the Apache 2.0 License.

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 DecodeLenient

func DecodeLenient[T any](rsp *http.Response, err error, ia *cassette.Interaction, debugFile string, out *T,
	opts json.Options,
) error

DecodeLenient is a debug-capable client's second try at a response body it could not decode as opts say, err being why. Decoding it the first time is the client's own, so that a client not in debug mode does nothing more than decode.

In debug mode, ia is the call the client recorded: DecodeLenient adds it to the interactions in debugFile, for openapi-enrich to learn from, and decodes the body ia recorded into out again, with members the specification does not know allowed, so that the response is still of use while they wait to be added. Without debug mode, ia is nil, and it returns err as a decoding error.

func NewErrBody

func NewErrBody(rsp *http.Response, body []byte) error

NewErrBody wraps an undecoded response body in an api.Error. Use this when the status code is unsuccessful and the API returns a body the specification gives no schema for, leaving nothing to decode it into.

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.

type ErrorBody

type ErrorBody struct {
	// The undecoded response body.
	Body []byte
}

ErrorBody is an error carrying a response body the specification declares no schema for, so nothing could be decoded from it.

func (*ErrorBody) Error

func (e *ErrorBody) Error() string

Error returns the error message: the body, truncated if it is long.

Directories

Path Synopsis
Package apitest holds what the tests openapi-codegen generates need, as net/http/httptest holds what tests of HTTP need: servers that answer as told, the replay of recorded interactions, and the checks of what a client decoded and of a type's round trip.
Package apitest holds what the tests openapi-codegen generates need, as net/http/httptest holds what tests of HTTP need: servers that answer as told, the replay of recorded interactions, and the checks of what a client decoded and of a type's round trip.
Package paging yields what an API lists a page at a time, fetching each page as the one before is used up.
Package paging yields what an API lists a page at a time, fetching each page as the one before is used up.
Package union holds what the code openapi-codegen generates decodes and encodes unions and tagged structs with: JSON values of several alternatives, of which the code chooses one by a discriminator, by the members an alternative requires and declares, or by a tag.
Package union holds what the code openapi-codegen generates decodes and encodes unions and tagged structs with: JSON values of several alternatives, of which the code chooses one by a discriminator, by the members an alternative requires and declares, or by a tag.

Jump to

Keyboard shortcuts

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