|
1 | | -import fetch from "node-fetch"; |
| 1 | +import fetch, { FetchError } from "node-fetch"; |
2 | 2 | import pkg from "../package.json" assert { type: "json" }; |
3 | | -import { ReplicateError } from "./errors.js"; |
| 3 | +import { |
| 4 | + ReplicateError, |
| 5 | + ReplicateRequestError, |
| 6 | + ReplicateResponseError, |
| 7 | +} from "./errors.js"; |
4 | 8 | import Prediction from "./Prediction.js"; |
5 | 9 | import { sleep } from "./utils.js"; |
6 | 10 |
|
@@ -70,30 +74,43 @@ export default class ReplicateClient { |
70 | 74 | async request(action, body) { |
71 | 75 | const { method, path } = this.#parseAction(action); |
72 | 76 |
|
| 77 | + const url = new URL(path, this.baseURL).href; |
| 78 | + const requestInit = { |
| 79 | + method, |
| 80 | + headers: this.#headers(), |
| 81 | + body: JSON.stringify(body), |
| 82 | + }; |
| 83 | + |
73 | 84 | let resp; |
74 | 85 | try { |
75 | | - resp = await fetch(new URL(path, this.baseURL).href, { |
76 | | - method, |
77 | | - headers: this.#headers(), |
78 | | - body: JSON.stringify(body), |
79 | | - }); |
| 86 | + resp = await fetch(url, requestInit); |
80 | 87 | } catch (err) { |
81 | | - // TODO: Better error handling. |
82 | | - throw err; |
| 88 | + if (!err instanceof FetchError) { |
| 89 | + throw err; |
| 90 | + } |
| 91 | + |
| 92 | + throw new ReplicateRequestError(url, requestInit); |
83 | 93 | } |
84 | 94 |
|
| 95 | + const respText = await resp.text(); |
| 96 | + |
85 | 97 | if (!resp.ok) { |
86 | | - // TODO: Better error handling. |
87 | | - console.error(await resp.text()); |
88 | | - throw new ReplicateError(resp.statusText); |
| 98 | + let errorMessage; |
| 99 | + try { |
| 100 | + const respJSON = JSON.parse(respText); |
| 101 | + errorMessage = respJSON.details; |
| 102 | + } catch (err) { |
| 103 | + if (!err instanceof SyntaxError) { |
| 104 | + throw err; |
| 105 | + } |
| 106 | + |
| 107 | + errorMessage = respText; |
| 108 | + } |
| 109 | + |
| 110 | + throw new ReplicateResponseError(errorMessage, resp, action); |
89 | 111 | } |
90 | 112 |
|
91 | | - try { |
92 | | - return await resp.json(); |
93 | | - } catch (err) { |
94 | | - // TODO: Better error handling. |
95 | | - throw err; |
96 | | - } |
| 113 | + return JSON.parse(respText); |
97 | 114 | } |
98 | 115 |
|
99 | 116 | #headers() { |
|
0 commit comments