http-errors.ts
ergonomic http errors as ts errors
import * as HttpStatus from 'http-status-codes';
export class HttpError extends Error {
status: string;
constructor(status: string | number, message?: string) {
super(message || HttpStatus.getReasonPhrase(+status));
this.status = `${status}`;
}
get text() {
return HttpStatus.getReasonPhrase(+this.status);
}
toResponse(message?: string) {
return new Response(`${this.message}${message ? ` - ${message}` : ''}`, {
status: +this.status,
headers: {
"Content-Type": "text/plain",
},
});
}
}
/**
HTTP error 400 - Bad Request
The request is generally malformed, invalid, or
contains invalid parameters.
*/
export class BadRequestError extends HttpError {
constructor(message?: string) {
super(400, message);
}
}
/**
HTTP error 409 - Conflict
The data as provided is in conflict with the state on
the server, perhaps because the server has been updated
elsewhere between this data being provided and being
submitted here.
*/
export class ConflictError extends HttpError {
constructor(message?: string) {
super(409, message);
}
}
/**
HTTP error 403 - Forbidden
The requested resource is forbidden to the requestor.
*/
export class ForbiddenError extends HttpError {
constructor(message?: string) {
super(403, message);
}
}
/**
HTTP error 410 - Gone
The requested data is no longer available.
*/
export class GoneError extends HttpError {
constructor(message?: string) {
super(410, message);
}
}
/**
HTTP error 500 - Internal Server Error
A general server occurred while handling the request.
*/
export class InternalServerError extends HttpError {
constructor(message?: string) {
super(500, message);
}
}
/**
HTTP error 404 - Not Found
The requested resource cannot be found.
*/
export class NotFoundError extends HttpError {
constructor(message?: string) {
super(404, message);
}
}
/**
HTTP error 501 - Not Implemented
The handling of the request is not implemented.
*/
export class NotImplementedError extends HttpError {
constructor(message?: string) {
super(501, message);
}
}
/**
HTTP error 503 - Service Unavailable
The server is not ready to handle the request.
*/
export class ServiceUnavailableError extends HttpError {
constructor(message?: string) {
super(503, message);
}
}
/**
HTTP error 401 - Unauthorized
The requested resource requires authorization to access.
*/
export class UnauthorizedError extends HttpError {
constructor(message?: string) {
super(401, message);
}
}
/**
HTTP error 422 - Unprocessable Entity
The provided data/inputs cannot be processed as provided (due to
validation errors, missing data, etc.).
*/
export class UnprocessableEntityError extends HttpError {
constructor(message?: string) {
super(422, message);
}
}