Merge branch '8784-dir-listings'
[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)
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 newTransactionError(req *http.Request, resp *http.Response, buf []byte) *TransactionError {
35         var e TransactionError
36         if json.Unmarshal(buf, &e) != nil {
37                 // No JSON-formatted error response
38                 e.errors = nil
39         }
40         e.Method = req.Method
41         e.URL = *req.URL
42         if resp != nil {
43                 e.Status = resp.Status
44                 e.StatusCode = resp.StatusCode
45         }
46         return &e
47 }