UNPKG

@aptly-as/types

Version:
65 lines (64 loc) 1.67 kB
export class AptlyError extends Error { static fromFetchResponse(response) { return AptlyError.fromResponse(response); } static async fromResponse(response) { const contentType = response.headers.get('content-type'); let body; if (contentType?.includes('application/json')) { body = await response.json(); if (!body.link) { body.link = response.url; } if (body.name === 'AptlyResponseError') { return new AptlyError(body); } } else { body = await response.text(); } throw new AptlyError({ id: 'unknown', status: response.status, message: response.statusText, detail: typeof body === 'object' ? JSON.stringify(body) : body, link: response.url, }); } constructor(data, error) { super(data.title || data.message); this.data = data; this.error = error; this.name = 'AptlyError'; this._status = 500; this._status = data.status; this.id = data.id || ''; } get status() { return this._status; } get title() { return this.data.message; } get code() { return this.data.code; } get detail() { return this.data.detail; } get link() { return this.data.link; } get errors() { return this.data.errors || []; } toJSON() { return { name: this.name, ...this.data, }; } toString() { return this.message; } }