-
Notifications
You must be signed in to change notification settings - Fork 68
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Added error handling for specific error codes #69
Conversation
It would be great if the |
Added Here is a brief example demonstrating how package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
)
var (
ErrorTooManyRequests = fmt.Errorf("too many requests")
)
type TooManyRequestsError struct {
Message string
RetryAfter int
}
func (e *TooManyRequestsError) Error() string {
return fmt.Sprintf("%s: retry_after %d", e.Message, e.RetryAfter)
}
func IsTooManyRequestsError(err error) bool {
_, ok := err.(*TooManyRequestsError)
return ok
}
type apiResponse struct {
OK bool `json:"ok"`
Result json.RawMessage `json:"result,omitempty"`
Description string `json:"description,omitempty"`
ErrorCode int `json:"error_code,omitempty"`
Parameters struct {
RetryAfter int `json:"retry_after"`
} `json:"parameters,omitempty"`
}
func rawRequest() error {
mockResponse := `{
"ok": false,
"error_code": 429,
"description": "Too Many Requests: retry after 35",
"parameters": {
"retry_after": 35
}
}`
body := strings.NewReader(mockResponse)
// Mocking an HTTP response
r := &http.Response{
StatusCode: http.StatusTooManyRequests,
Body: io.NopCloser(body),
}
// Parse API response
var apiResp apiResponse
errDecode := json.NewDecoder(r.Body).Decode(&apiResp)
if errDecode != nil {
return fmt.Errorf("error decoding API response: %w", errDecode)
}
if apiResp.ErrorCode == 429 {
err := &TooManyRequestsError{
Message: fmt.Sprintf("%w, %s", ErrorTooManyRequests, apiResp.Description),
RetryAfter: apiResp.Parameters.RetryAfter,
}
return err
}
return nil
}
func main() {
err := rawRequest()
if err != nil {
if IsTooManyRequestsError(err) {
fmt.Println("Received TooManyRequestsError with retry_after:", err.(*TooManyRequestsError).RetryAfter)
} else {
fmt.Println("Received error:", err)
}
} else {
fmt.Println("No error received.")
}
} |
fix: changed from %w to %s to ensure proper functionality of Sprintf
Added error handling for specific HTTP status codes in accordance with the Telegram API specifications.
Changes:
Benefits: