1package auth
2
3import (
4	"encoding/json"
5	"net/http"
6
7	"github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox"
8)
9
10// AuthAPIError wraps AuthError
11type AuthAPIError struct {
12	dropbox.APIError
13	AuthError *AuthError `json:"error"`
14}
15
16// AccessAPIError wraps AccessError
17type AccessAPIError struct {
18	dropbox.APIError
19	AccessError *AccessError `json:"error"`
20}
21
22// RateLimitAPIError wraps RateLimitError
23type RateLimitAPIError struct {
24	dropbox.APIError
25	RateLimitError *RateLimitError `json:"error"`
26}
27
28// Bad input parameter.
29type BadRequest struct {
30	dropbox.APIError
31}
32
33// An error occurred on the Dropbox servers. Check status.dropbox.com for announcements about
34// Dropbox service issues.
35type ServerError struct {
36	dropbox.APIError
37	StatusCode int
38}
39
40func ParseError(err error, appError error) error {
41	sdkErr, ok := err.(dropbox.SDKInternalError)
42	if !ok {
43		return err
44	}
45
46	if sdkErr.StatusCode >= 500 && sdkErr.StatusCode <= 599 {
47		return ServerError{
48			APIError: dropbox.APIError{
49				ErrorSummary: sdkErr.Content,
50			},
51		}
52	}
53
54	switch sdkErr.StatusCode {
55	case http.StatusBadRequest:
56		return BadRequest{
57			APIError: dropbox.APIError{
58				ErrorSummary: sdkErr.Content,
59			},
60		}
61	case http.StatusUnauthorized:
62		var apiError AuthAPIError
63		if pErr := json.Unmarshal([]byte(sdkErr.Content), &apiError); pErr != nil {
64			return pErr
65		}
66
67		return apiError
68	case http.StatusForbidden:
69		var apiError AccessAPIError
70		if pErr := json.Unmarshal([]byte(sdkErr.Content), &apiError); pErr != nil {
71			return pErr
72		}
73
74		return apiError
75	case http.StatusTooManyRequests:
76		var apiError RateLimitAPIError
77		if pErr := json.Unmarshal([]byte(sdkErr.Content), &apiError); pErr != nil {
78			return pErr
79		}
80
81		return apiError
82	case http.StatusConflict:
83		if pErr := json.Unmarshal([]byte(sdkErr.Content), appError); pErr != nil {
84			return pErr
85		}
86
87		return appError
88	}
89
90	return err
91}
92