Skip to content

Commit 4714f73

Browse files
committed
fix: correct handling of http errors
1 parent d83b106 commit 4714f73

1 file changed

Lines changed: 10 additions & 35 deletions

File tree

src/core/rest-client.ts

Lines changed: 10 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { Buffer } from 'node:buffer'
2-
import { FormatError, HttpError, ServerError, TokenError } from '../errors'
2+
import { FormatError, HttpError, TokenError } from '../errors'
33
import type { HttpMethod, Options, RequestInit } from '../typings/lib'
44
import { AsyncQueue } from './async-queue'
55

@@ -23,44 +23,17 @@ export class RestClient {
2323
throw new TokenError('No access token provided')
2424
}
2525

26-
private async handleHTTPError(res: Response, parsedBody: any): Promise<void> {
27-
if (res.status === 400) {
28-
throw new FormatError(
29-
this.extractErrorMessage(parsedBody),
30-
`${res.status} ${res.statusText}, ${res.url}`,
31-
)
32-
}
33-
else if (res.status === 401) {
34-
throw new TokenError(this.extractErrorMessage(parsedBody, 'Empty'))
35-
}
36-
else if (res.status >= 500) {
37-
throw new ServerError(String(res.status))
38-
}
39-
else {
40-
throw new HttpError(
41-
this.extractErrorMessage(parsedBody, `${res.status} ${res.statusText}, ${res.url}`),
42-
)
43-
}
44-
}
26+
private async checkHttpError(res: Response): Promise<void> {
27+
if (res.ok || res.status === 204)
28+
return
4529

46-
private extractErrorMessage(parsedBody: any, defaultMsg?: string): string {
47-
if (typeof parsedBody === 'object' && parsedBody !== null) {
48-
if (parsedBody.error_message)
49-
return parsedBody.error_message
50-
if (parsedBody.result && parsedBody.result.error_message)
51-
return parsedBody.result.error_message
52-
if (parsedBody.error)
53-
return parsedBody.error
54-
}
55-
return defaultMsg || 'Unknown Error'
30+
if (res.headers.get('Content-Type') === 'application/problem+json')
31+
throw new FormatError(res.body ? await res.json() : 'Error', `${res.status} ${res.statusText}, ${res.url}`)
32+
else
33+
throw new HttpError(res.body ? await res.text() : `${res.status} ${res.statusText}, ${res.url}`)
5634
}
5735

5836
private async validateResponse(res: Response, body: any): Promise<void> {
59-
if (!res.ok || res.status === 204) {
60-
this.handleHTTPError(res, body)
61-
return
62-
}
63-
6437
if (body.success === false) {
6538
if (body.error === 'Неавторизованное API-обращение')
6639
throw new TokenError(body.error)
@@ -103,6 +76,8 @@ export class RestClient {
10376
body: bodyData,
10477
})
10578

79+
await this.checkHttpError(res)
80+
10681
const parsedBody = res.body ? ((await res.json()) as T) : (null as T)
10782
await this.validateResponse(res, parsedBody)
10883

0 commit comments

Comments
 (0)