aboutsummaryrefslogtreecommitdiff
path: root/web/vastai/error.go
blob: 89487a7734c40859938e6806a50fb5dc3e289030 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package vastai

import (
	"encoding/json"
	"fmt"
	"net/http"
)

type Error struct {
	Success    bool   `json:"success"`
	ErrorKind  string `json:"error"`
	Msg        string `json:"msg"`
	StatusCode int    `json:"status_code"`
}

func (e Error) Error() string {
	return fmt.Sprintf("%s (%d): %s", e.ErrorKind, e.StatusCode, e.Msg)
}

func NewError(resp *http.Response) error {
	var e Error

	dec := json.NewDecoder(resp.Body)
	defer resp.Body.Close()
	if err := dec.Decode(&e); err != nil {
		return fmt.Errorf("vastai: can't decode json while handling error: %w", err)
	}

	e.StatusCode = resp.StatusCode

	return e
}