diff --git a/plugins/octopus-deploy/src/api/index.ts b/plugins/octopus-deploy/src/api/index.ts index dae508d172..843f304015 100644 --- a/plugins/octopus-deploy/src/api/index.ts +++ b/plugins/octopus-deploy/src/api/index.ts @@ -117,74 +117,19 @@ export class OctopusDeployClient implements OctopusDeployApi { releaseHistoryCount: number; }): Promise { const url = await this.getProgressionApiUrl(opts); - - const response = await this.fetchApi.fetch(url); - - let responseJson; - - try { - responseJson = await response.json(); - } catch (e) { - responseJson = { releases: [] }; - } - - if (response.status !== 200) { - throw new Error( - `Error communicating with Octopus Deploy: ${ - responseJson?.error?.title || response.statusText - }`, - ); - } - - return responseJson; + return this.fetchAndHandleErrors(url); } async getProjectInfo( projectReference: ProjectReference, ): Promise { const url = await this.getProjectApiUrl(projectReference); - const response = await this.fetchApi.fetch(url); - - let responseJson; - - try { - responseJson = await response.json(); - } catch (e) { - responseJson = { releases: [] }; - } - - if (response.status !== 200) { - throw new Error( - `Error communicating with Octopus Deploy: ${ - responseJson?.error?.title || response.statusText - }`, - ); - } - - return responseJson; + return this.fetchAndHandleErrors(url); } async getProjectGroups(): Promise { const url = await this.getProjectGroupApiUrl(); - const response = await this.fetchApi.fetch(url); - - let responseJson; - - try { - responseJson = await response.json(); - } catch (e) { - responseJson = { releases: [] }; - } - - if (response.status !== 200) { - throw new Error( - `Error communicating with Octopus Deploy: ${ - responseJson?.error?.title || response.statusText - }`, - ); - } - - return responseJson; + return this.fetchAndHandleErrors(url); } async getConfig(): Promise { @@ -193,6 +138,26 @@ export class OctopusDeployClient implements OctopusDeployApi { }; } + private async fetchAndHandleErrors(url: string): Promise { + const response = await this.fetchApi.fetch(url); + + let responseJson: T; + + try { + responseJson = await response.json(); + } catch (e) { + throw new Error(`Failed to parse JSON response: ${e}`); + } + + if (!response.ok) { + throw new Error( + `Error communicating with Octopus Deploy: ${response.status}`, + ); + } + + return responseJson; + } + private async getProgressionApiUrl(opts: { projectReference: ProjectReference; releaseHistoryCount: number;