Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,6 @@ make docs-sync # 公式APIドキュメントを docs/v2/ に同期
1. **nil安全性**: APIレスポンスの欠損フィールドはポインタで表現
2. **型変換**: APIはJSONの型を不整合に返すことがあるため、`types`パッケージのカスタム型で処理
3. **定数定義**: 市場区分コード、業種コード、開示書類種別などは定数として定義済み(再定義しない)
4. **エラー**: HTTPステータス起因のエラーは `client.APIError`(`client/errors.go`)で返す。利用側は `errors.As` やヘルパー(`client.IsRateLimitExceeded` など)で判定する
- `APIError.Error()` の書式 `API error: status=%d, body=%s` は後方互換のため変更しない(`client/errors_test.go` で固定)
- サービス側でエラーを包む際は必ず `%w` を使う(`errors.As` を壊さないため)
42 changes: 42 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,48 @@ size := httpClient.CacheSize()
- 署名付きダウンロードURLを返すAPI(Bulk・TDnetのファイルURL取得)はURLが失効するためキャッシュを経由しません
- キャッシュはクライアントインスタンスの生存期間のみ有効です

## エラーハンドリング

APIがエラーステータスを返した場合は `*client.APIError` が返ります。各サービスはこれを `%w` でラップするため、`errors.As` でステータスコードとレスポンスボディを取り出せます。

```go
quotes, err := jq.Quotes.GetDailyQuotesByCode(ctx, "7203")

var apiErr *client.APIError
if errors.As(err, &apiErr) {
log.Printf("status=%d body=%s", apiErr.StatusCode, apiErr.Body)
}
```

利用頻度の高い判定にはヘルパーを用意しています。

| ヘルパー | 対象ステータス |
|---------|--------------|
| `client.IsRateLimitExceeded(err)` | 429 |
| `client.IsAuthError(err)` | 401, 403 |
| `client.IsServerError(err)` | 5xx |
| `client.StatusCode(err)` | 任意(`(code int, ok bool)` を返す) |

```go
for {
quotes, err := jq.Quotes.GetDailyQuotesByCode(ctx, "7203")
switch {
case err == nil:
return quotes, nil
case client.IsRateLimitExceeded(err):
time.Sleep(time.Minute) // 待機してから再試行
case client.IsServerError(err):
time.Sleep(10 * time.Second)
default:
return nil, err // 認証エラー・パラメータ不正などは再試行しても解決しない
}
}
```

- 403はAPIキーが不正な場合のほか、契約プランに含まれないデータへアクセスした場合にも返ります
- データが存在しない場合に210を返すAPI(前場四本値など)があり、これも `*client.APIError`(`StatusCode` が210)になります
- 通信エラーやレスポンスのデコードエラーは `*client.APIError` にならないため、`client.StatusCode` の `ok` は false になります

## 利用可能なAPI

このライブラリでは以下のAPIエンドポイントにアクセスできます。
Expand Down
2 changes: 1 addition & 1 deletion client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ func (c *Client) doHTTPRequest(ctx context.Context, method, path string, body in
}

if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API error: status=%d, body=%s", resp.StatusCode, string(respBody))
return nil, &APIError{StatusCode: resp.StatusCode, Body: string(respBody)}
}

return respBody, nil
Expand Down
67 changes: 67 additions & 0 deletions client/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package client

import (
"errors"
"fmt"
"net/http"
)

// APIError is returned when the J-Quants API responds with a status other than
// 200 OK. It carries the raw status code and response body so that callers can
// branch on the status instead of parsing the error message.
//
// var apiErr *client.APIError
// if errors.As(err, &apiErr) {
// log.Printf("status=%d body=%s", apiErr.StatusCode, apiErr.Body)
// }
//
// Service methods wrap the error with %w, so errors.As works on the error
// returned by any service method.
type APIError struct {
// StatusCode is the HTTP status code returned by the API.
StatusCode int
// Body is the raw response body. The API returns a JSON object such as
// {"message": "..."} for most errors, but this is not guaranteed.
Body string
}

// Error implements the error interface. The format is fixed for backward
// compatibility with callers that match on the message.
func (e *APIError) Error() string {
return fmt.Sprintf("API error: status=%d, body=%s", e.StatusCode, e.Body)
}

// StatusCode returns the HTTP status code carried by err. ok is false when err
// is not (and does not wrap) an *APIError, which is the case for transport,
// context and decoding errors.
func StatusCode(err error) (code int, ok bool) {
var apiErr *APIError
if errors.As(err, &apiErr) {
return apiErr.StatusCode, true
}
return 0, false
}

// IsRateLimitExceeded reports whether err is an API error caused by exceeding
// the rate limit (429). Wait before retrying: repeating requests while over the
// limit can block access for about five minutes.
func IsRateLimitExceeded(err error) bool {
code, ok := StatusCode(err)
return ok && code == http.StatusTooManyRequests
}

// IsAuthError reports whether err is an API error caused by authentication or
// authorization (401, 403). The API returns 403 for an invalid API key as well
// as for data that is not included in the contracted plan, so retrying does not
// help.
func IsAuthError(err error) bool {
code, ok := StatusCode(err)
return ok && (code == http.StatusUnauthorized || code == http.StatusForbidden)
}

// IsServerError reports whether err is an API error with a 5xx status. These
// are usually temporary and can be retried after a delay.
func IsServerError(err error) bool {
code, ok := StatusCode(err)
return ok && code >= 500 && code <= 599
}
239 changes: 239 additions & 0 deletions client/errors_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
package client

import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
)

// TestAPIError_Error は Error() の文字列書式を固定する。
// 既存の利用者がメッセージに依存している可能性があるため、書式は変更しない。
func TestAPIError_Error(t *testing.T) {
tests := []struct {
name string
err *APIError
want string
}{
{
name: "rate limit",
err: &APIError{StatusCode: 429, Body: `{"message":"Too Many Requests"}`},
want: `API error: status=429, body={"message":"Too Many Requests"}`,
},
{
name: "forbidden",
err: &APIError{StatusCode: 403, Body: `{"message":"Forbidden"}`},
want: `API error: status=403, body={"message":"Forbidden"}`,
},
{
name: "empty body",
err: &APIError{StatusCode: 500, Body: ""},
want: "API error: status=500, body=",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.err.Error(); got != tt.want {
t.Errorf("Error() = %q, want %q", got, tt.want)
}
})
}
}

func TestAPIError_As(t *testing.T) {
base := &APIError{StatusCode: 429, Body: `{"message":"Too Many Requests"}`}

tests := []struct {
name string
err error
}{
{name: "direct", err: base},
{name: "wrapped once", err: fmt.Errorf("failed to get daily quotes: %w", base)},
{name: "wrapped twice", err: fmt.Errorf("outer: %w", fmt.Errorf("failed to get daily quotes: %w", base))},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var apiErr *APIError
if !errors.As(tt.err, &apiErr) {
t.Fatalf("errors.As failed for %v", tt.err)
}
if apiErr.StatusCode != 429 {
t.Errorf("StatusCode = %d, want 429", apiErr.StatusCode)
}
if apiErr.Body != base.Body {
t.Errorf("Body = %q, want %q", apiErr.Body, base.Body)
}
if !IsRateLimitExceeded(tt.err) {
t.Error("IsRateLimitExceeded = false, want true")
}
})
}
}

// TestStatusCode_MisleadingMessage はボディに 401 や 429 という数字列が含まれていても、
// 実際のステータスコードで判定されることを確認する。
func TestStatusCode_MisleadingMessage(t *testing.T) {
// 銘柄コードやメッセージ本文に、他のステータスコードと一致する数字列が含まれるケース
body := `{"message":"invalid code 4290 (401k related), see status 429 doc"}`
err := fmt.Errorf("failed to get daily quotes: %w", &APIError{StatusCode: http.StatusBadRequest, Body: body})

// 文字列マッチであれば誤判定するボディであることを確認する
if !strings.Contains(err.Error(), "429") || !strings.Contains(err.Error(), "401") {
t.Fatal("test fixture must contain misleading 401/429 digits")
}

code, ok := StatusCode(err)
if !ok || code != http.StatusBadRequest {
t.Errorf("StatusCode() = (%d, %v), want (400, true)", code, ok)
}
if IsRateLimitExceeded(err) {
t.Error("IsRateLimitExceeded = true for a 400 response containing '429'")
}
if IsAuthError(err) {
t.Error("IsAuthError = true for a 400 response containing '401'")
}
if IsServerError(err) {
t.Error("IsServerError = true for a 400 response")
}
}

func TestErrorPredicates(t *testing.T) {
tests := []struct {
name string
err error
wantCode int
wantOK bool
wantRateLimited bool
wantAuth bool
wantServer bool
}{
{name: "400", err: &APIError{StatusCode: 400}, wantCode: 400, wantOK: true},
{name: "401", err: &APIError{StatusCode: 401}, wantCode: 401, wantOK: true, wantAuth: true},
{name: "403", err: &APIError{StatusCode: 403}, wantCode: 403, wantOK: true, wantAuth: true},
{name: "429", err: &APIError{StatusCode: 429}, wantCode: 429, wantOK: true, wantRateLimited: true},
{name: "500", err: &APIError{StatusCode: 500}, wantCode: 500, wantOK: true, wantServer: true},
{name: "503", err: &APIError{StatusCode: 503}, wantCode: 503, wantOK: true, wantServer: true},
// 210 (No Content) はデータ無しを示すステータスで、5xx ではない
{name: "210", err: &APIError{StatusCode: 210}, wantCode: 210, wantOK: true},
{name: "nil", err: nil},
{name: "context canceled", err: context.Canceled},
{name: "non-API error", err: errors.New("API error: status=429, body=oops")},
{name: "wrapped non-API error", err: fmt.Errorf("failed to send request: %w", context.DeadlineExceeded)},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
code, ok := StatusCode(tt.err)
if code != tt.wantCode || ok != tt.wantOK {
t.Errorf("StatusCode() = (%d, %v), want (%d, %v)", code, ok, tt.wantCode, tt.wantOK)
}
if got := IsRateLimitExceeded(tt.err); got != tt.wantRateLimited {
t.Errorf("IsRateLimitExceeded() = %v, want %v", got, tt.wantRateLimited)
}
if got := IsAuthError(tt.err); got != tt.wantAuth {
t.Errorf("IsAuthError() = %v, want %v", got, tt.wantAuth)
}
if got := IsServerError(tt.err); got != tt.wantServer {
t.Errorf("IsServerError() = %v, want %v", got, tt.wantServer)
}
})
}
}

func TestClient_DoRequest_APIError(t *testing.T) {
const body = `{"message":"Too Many Requests"}`
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusTooManyRequests)
_, _ = w.Write([]byte(body))
}))
defer server.Close()

c := NewClient("test-api-key")
c.baseURL = server.URL

var resp struct{ Message string }
err := c.DoRequest(context.Background(), http.MethodGet, "/test", nil, &resp)
if err == nil {
t.Fatal("expected an error")
}

var apiErr *APIError
if !errors.As(err, &apiErr) {
t.Fatalf("errors.As failed for %v", err)
}
if apiErr.StatusCode != http.StatusTooManyRequests {
t.Errorf("StatusCode = %d, want 429", apiErr.StatusCode)
}
if apiErr.Body != body {
t.Errorf("Body = %q, want %q", apiErr.Body, body)
}
if !IsRateLimitExceeded(err) {
t.Error("IsRateLimitExceeded = false, want true")
}
// 既存の利用者のためにメッセージ書式を維持する
want := "API error: status=429, body=" + body
if err.Error() != want {
t.Errorf("Error() = %q, want %q", err.Error(), want)
}
}

func TestClient_DoRequest_APIErrorWithCache(t *testing.T) {
var callCount int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(`{"message":"Forbidden"}`))
}))
defer server.Close()

c := NewClient("test-api-key", WithCache())
c.baseURL = server.URL

// キャッシュ有効時(singleflight経由)でも同じ型が返る
var resp struct{ Message string }
err := c.DoRequest(context.Background(), http.MethodGet, "/test", nil, &resp)
if !IsAuthError(err) {
t.Fatalf("IsAuthError = false for %v", err)
}

// エラーレスポンスはキャッシュされない
if c.CacheSize() != 0 {
t.Errorf("expected error response not to be cached, got %d entries", c.CacheSize())
}
if err := c.DoRequest(context.Background(), http.MethodGet, "/test", nil, &resp); !IsAuthError(err) {
t.Errorf("IsAuthError = false for %v", err)
}
if callCount != 2 {
t.Errorf("expected 2 calls, got %d", callCount)
}

// DoRequestNoCache も同様
if err := c.DoRequestNoCache(context.Background(), http.MethodGet, "/test", nil, &resp); !IsAuthError(err) {
t.Errorf("IsAuthError = false for %v", err)
}
}

func TestClient_DoRequest_NonAPIError(t *testing.T) {
// ステータスは200だがボディがJSONではない場合、APIErrorにはならない
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("not json"))
}))
defer server.Close()

c := NewClient("test-api-key")
c.baseURL = server.URL

var resp struct{ Message string }
err := c.DoRequest(context.Background(), http.MethodGet, "/test", nil, &resp)
if err == nil {
t.Fatal("expected an error")
}
if code, ok := StatusCode(err); ok {
t.Errorf("StatusCode() = (%d, true), want ok=false for a decode error", code)
}
}
Loading
Loading