apierror.go

 1// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
 2
 3package apierror
 4
 5import (
 6	"fmt"
 7	"net/http"
 8	"net/http/httputil"
 9
10	"github.com/openai/openai-go/internal/apijson"
11	"github.com/openai/openai-go/packages/resp"
12)
13
14// Error represents an error that originates from the API, i.e. when a request is
15// made and the API returns a response with a HTTP status code. Other errors are
16// not wrapped by this SDK.
17type Error struct {
18	Code    string `json:"code,required"`
19	Message string `json:"message,required"`
20	Param   string `json:"param,required"`
21	Type    string `json:"type,required"`
22	// Metadata for the response, check the presence of optional fields with the
23	// [resp.Field.IsPresent] method.
24	JSON struct {
25		Code        resp.Field
26		Message     resp.Field
27		Param       resp.Field
28		Type        resp.Field
29		ExtraFields map[string]resp.Field
30		raw         string
31	} `json:"-"`
32	StatusCode int
33	Request    *http.Request
34	Response   *http.Response
35}
36
37// Returns the unmodified JSON received from the API
38func (r Error) RawJSON() string { return r.JSON.raw }
39func (r *Error) UnmarshalJSON(data []byte) error {
40	return apijson.UnmarshalRoot(data, r)
41}
42
43func (r *Error) Error() string {
44	// Attempt to re-populate the response body
45	return fmt.Sprintf("%s %q: %d %s %s", r.Request.Method, r.Request.URL, r.Response.StatusCode, http.StatusText(r.Response.StatusCode), r.JSON.raw)
46}
47
48func (r *Error) DumpRequest(body bool) []byte {
49	if r.Request.GetBody != nil {
50		r.Request.Body, _ = r.Request.GetBody()
51	}
52	out, _ := httputil.DumpRequestOut(r.Request, body)
53	return out
54}
55
56func (r *Error) DumpResponse(body bool) []byte {
57	out, _ := httputil.DumpResponse(r.Response, body)
58	return out
59}