1
0
mirror of https://github.com/dstotijn/go-notion.git synced 2024-11-24 08:42:26 +02:00

Simplify APIError.Unwrap, fix missing error message prefixes

This commit is contained in:
David Stotijn 2021-05-14 18:24:56 +02:00
parent d9867284b5
commit fccdde0f5b
2 changed files with 23 additions and 29 deletions

View File

@ -91,22 +91,22 @@ type DatabaseProperty struct {
func (c *Client) FindDatabaseByID(id string) (db Database, err error) {
req, err := c.newRequest("GET", "/databases/"+id, nil)
if err != nil {
return Database{}, fmt.Errorf("invalid URL: %w", err)
return Database{}, fmt.Errorf("notion: invalid URL: %w", err)
}
res, err := c.httpClient.Do(req)
if err != nil {
return Database{}, fmt.Errorf("failed to make HTTP request: %w", err)
return Database{}, fmt.Errorf("notion: failed to make HTTP request: %w", err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
return Database{}, fmt.Errorf("notion: failed to get database: %w", parseErrorResponse(res))
return Database{}, fmt.Errorf("notion: failed to find database: %w", parseErrorResponse(res))
}
err = json.NewDecoder(res.Body).Decode(&db)
if err != nil {
return Database{}, fmt.Errorf("failed to parse HTTP response: %w", err)
return Database{}, fmt.Errorf("notion: failed to parse HTTP response: %w", err)
}
return db, nil

View File

@ -22,6 +22,20 @@ var (
ErrServiceUnavailable = errors.New("notion: service is unavailable")
)
var errMap = map[string]error{
"invalid_json": ErrInvalidJSON,
"invalid_request_url": ErrInvalidRequestURL,
"invalid_request": ErrInvalidRequest,
"validation_error": ErrValidation,
"unauthorized": ErrUnauthorized,
"restricted_resource": ErrRestrictedResource,
"object_not_found": ErrObjectNotFound,
"conflict_error": ErrConflict,
"rate_limited": ErrRateLimited,
"internal_server_error": ErrInternalServer,
"service_unavailable": ErrServiceUnavailable,
}
type APIError struct {
Object string `json:"object"`
Status int `json:"status"`
@ -35,32 +49,12 @@ func (err *APIError) Error() string {
}
func (err *APIError) Unwrap() error {
switch err.Code {
case "invalid_json":
return ErrInvalidJSON
case "invalid_request_url":
return ErrInvalidRequestURL
case "invalid_request":
return ErrInvalidRequest
case "validation_error":
return ErrValidation
case "unauthorized":
return ErrUnauthorized
case "restricted_resource":
return ErrRestrictedResource
case "object_not_found":
return ErrObjectNotFound
case "conflict_error":
return ErrConflict
case "rate_limited":
return ErrRateLimited
case "internal_server_error":
return ErrInternalServer
case "service_unavailable":
return ErrServiceUnavailable
default:
return fmt.Errorf("notion: unknown error (%v)", err.Code)
mapped, ok := errMap[err.Code]
if !ok {
return fmt.Errorf("notion: %v", err.Error())
}
return mapped
}
func parseErrorResponse(res *http.Response) error {