Merge branch '12430-output-glob'
[arvados.git] / sdk / go / arvados / error.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 package arvados
6
7 import (
8         "encoding/json"
9         "fmt"
10         "net/http"
11         "net/url"
12         "strings"
13 )
14
15 type TransactionError struct {
16         Method     string
17         URL        url.URL
18         StatusCode int
19         Status     string
20         Errors     []string
21 }
22
23 func (e TransactionError) Error() (s string) {
24         s = fmt.Sprintf("request failed: %s", e.URL.String())
25         if e.Status != "" {
26                 s = s + ": " + e.Status
27         }
28         if len(e.Errors) > 0 {
29                 s = s + ": " + strings.Join(e.Errors, "; ")
30         }
31         return
32 }
33
34 func (e TransactionError) HTTPStatus() int {
35         return e.StatusCode
36 }
37
38 func newTransactionError(req *http.Request, resp *http.Response, buf []byte) *TransactionError {
39         var e TransactionError
40         if json.Unmarshal(buf, &e) != nil {
41                 // No JSON-formatted error response
42                 e.Errors = nil
43         }
44         e.Method = req.Method
45         e.URL = *req.URL
46         if resp != nil {
47                 e.Status = resp.Status
48                 e.StatusCode = resp.StatusCode
49         }
50         return &e
51 }