diff --git a/src/http-api/errors.ts b/src/http-api/errors.ts index cf057aff7..1610a8623 100644 --- a/src/http-api/errors.ts +++ b/src/http-api/errors.ts @@ -22,6 +22,19 @@ interface IErrorJson extends Partial { error?: string; } +/** + * Construct a generic HTTP error. This is a JavaScript Error with additional information + * specific to HTTP responses. + * @constructor + * @param {string} msg The error message to include. + * @param {number} httpStatus The HTTP response status code. + */ +export class HTTPError extends Error { + constructor(msg: string, public readonly httpStatus?: number) { + super(msg); + } +} + /** * Construct a Matrix error. This is a JavaScript Error with additional * information specific to the standard Matrix error response. @@ -33,11 +46,11 @@ interface IErrorJson extends Partial { * @prop {Object} data The raw Matrix error JSON used to construct this object. * @prop {number} httpStatus The numeric HTTP status code given */ -export class MatrixError extends Error { +export class MatrixError extends HTTPError { public readonly errcode?: string; public readonly data: IErrorJson; - constructor(errorJson: IErrorJson = {}, public httpStatus?: number, public url?: string) { + constructor(errorJson: IErrorJson = {}, public readonly httpStatus?: number, public url?: string) { let message = errorJson.error || "Unknown message"; if (httpStatus) { message = `[${httpStatus}] ${message}`; @@ -45,7 +58,7 @@ export class MatrixError extends Error { if (url) { message = `${message} (${url})`; } - super(`MatrixError: ${message}`); + super(`MatrixError: ${message}`, httpStatus); this.errcode = errorJson.errcode; this.name = errorJson.errcode || "Unknown error code"; this.data = errorJson; diff --git a/src/http-api/utils.ts b/src/http-api/utils.ts index ac0eafb4b..21ddfb9dd 100644 --- a/src/http-api/utils.ts +++ b/src/http-api/utils.ts @@ -18,7 +18,7 @@ import { parse as parseContentType, ParsedMediaType } from "content-type"; import { logger } from "../logger"; import { sleep } from "../utils"; -import { ConnectionError, MatrixError } from "./errors"; +import { ConnectionError, HTTPError, MatrixError } from "./errors"; // Ponyfill for https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout export function timeoutSignal(ms: number): AbortSignal { @@ -87,9 +87,9 @@ export function parseErrorResponse(response: XMLHttpRequest | Response, body?: s ); } if (contentType?.type === "text/plain") { - return new Error(`Server returned ${response.status} error: ${body}`); + return new HTTPError(`Server returned ${response.status} error: ${body}`, response.status); } - return new Error(`Server returned ${response.status} error`); + return new HTTPError(`Server returned ${response.status} error`, response.status); } function isXhr(response: XMLHttpRequest | Response): response is XMLHttpRequest {