swaf/src/HttpError.ts

101 lines
2.5 KiB
TypeScript
Raw Normal View History

import {WrappingError} from "./Utils.js";
2020-04-22 15:52:17 +02:00
export abstract class HttpError extends WrappingError {
public readonly instructions: string;
2020-07-08 11:33:01 +02:00
protected constructor(message: string, instructions: string, cause?: Error) {
2020-04-22 15:52:17 +02:00
super(message, cause);
this.instructions = instructions;
}
public get name(): string {
2020-04-22 15:52:17 +02:00
return this.constructor.name;
}
2021-11-09 19:45:20 +01:00
public abstract get errorCode(): number;
2020-04-22 15:52:17 +02:00
}
export class BadRequestError extends HttpError {
public readonly url: string;
public constructor(message: string, instructions: string, url: string, cause?: Error) {
2020-04-22 15:52:17 +02:00
super(message, instructions, cause);
this.url = url;
}
public get errorCode(): number {
2020-04-22 15:52:17 +02:00
return 400;
}
}
2020-07-08 11:33:01 +02:00
export class UnauthorizedHttpError extends BadRequestError {
public constructor(message: string, url: string, cause?: Error) {
2020-07-08 11:33:01 +02:00
super(message, '', url, cause);
}
public get errorCode(): number {
2020-07-08 11:33:01 +02:00
return 401;
}
}
2020-04-22 15:52:17 +02:00
export class ForbiddenHttpError extends BadRequestError {
public constructor(thing: string, url: string, cause?: Error) {
2020-04-22 15:52:17 +02:00
super(
`You don't have access to this ${thing}.`,
`${url} doesn't belong to *you*.`,
url,
cause,
2020-04-22 15:52:17 +02:00
);
}
public get errorCode(): number {
2020-04-22 15:52:17 +02:00
return 403;
}
}
export class NotFoundHttpError extends BadRequestError {
public constructor(thing: string, url: string, cause?: Error) {
2020-04-22 15:52:17 +02:00
super(
`${thing.charAt(0).toUpperCase()}${thing.substr(1)} not found.`,
`${url} doesn't exist or was deleted.`,
url,
cause,
2020-04-22 15:52:17 +02:00
);
}
public get errorCode(): number {
2020-04-22 15:52:17 +02:00
return 404;
}
}
export class TooManyRequestsHttpError extends BadRequestError {
2020-11-15 15:16:18 +01:00
public constructor(retryIn: number, jailName: string, cause?: Error) {
super(
`You're making too many requests!`,
`We need some rest. Please retry in ${Math.floor(retryIn / 1000)} seconds.`,
2020-11-15 15:16:18 +01:00
jailName,
cause,
);
}
public get errorCode(): number {
2020-04-24 11:11:03 +02:00
return 429;
}
}
2020-04-22 15:52:17 +02:00
export class ServerError extends HttpError {
public constructor(message: string, cause?: Error) {
2020-04-22 15:52:17 +02:00
super(message, `Maybe you should contact us; see instructions below.`, cause);
}
public get errorCode(): number {
2020-04-22 15:52:17 +02:00
return 500;
}
}
export class ServiceUnavailableHttpError extends ServerError {
public get errorCode(): number {
2020-04-22 15:52:17 +02:00
return 503;
}
}