ufiber
Version:
Next-gen webserver for node-js developer
96 lines (94 loc) • 2.89 kB
JavaScript
import { HttpStatus } from "./status.js";
//#region src/errors.ts
const nameCache = /* @__PURE__ */ new Map();
/**
* Get a human-readable error name from the HTTP status code.
*/
const getErrorName = (status) => {
if (nameCache.has(status)) return nameCache.get(status);
if (status < 400 || status > 511) return "HttpError";
const rawName = HttpStatus[`${status}_NAME`];
if (!rawName) return "HttpError";
const camel = rawName.replace(/[^a-zA-Z0-9 ]+/g, "").split(/\s+/).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
const finalName = camel.endsWith("Error") ? camel : `${camel}Error`;
nameCache.set(status, finalName);
return finalName;
};
/**
* Base class for handling HTTP errors.
*/
var HttpError = class HttpError extends Error {
/**
* Creates an instance of `HttpError`.
*/
constructor(status = HttpStatus.INTERNAL_SERVER_ERROR, options = { message: "HttpError" }) {
super(typeof options.message === "string" ? options.message : getErrorName(status));
this.status = status;
this.options = options;
this.name = options.name ?? getErrorName(status);
Error.captureStackTrace?.(this, this.constructor);
}
static isError(value) {
return value instanceof HttpError;
}
getBody() {
const { name: error, status } = this;
const { message, data = null, code = null } = this.options;
return {
status,
error,
message,
data,
code
};
}
};
/**
* Utility to create custom HttpError subclasses with optional custom naming.
*/
const createHttpError = (status, defaultName) => class extends HttpError {
constructor(message, options = {}) {
super(status, {
message,
...options,
name: options.name ?? defaultName
});
}
};
/**
* Represents a Bad Request HTTP error (400).
* @extends {HttpError}
*/
const BadRequestError = createHttpError(HttpStatus.BAD_REQUEST);
/**
* Represents a Conflict HTTP error (409).
* @extends {HttpError}
*/
const ConflictError = createHttpError(HttpStatus.CONFLICT);
/**
* Represents a Forbidden HTTP error (403).
* @extends {HttpError}
*/
const ForbiddenError = createHttpError(HttpStatus.FORBIDDEN);
/**
* Represents a Not Found HTTP error (404).
* @extends {HttpError}
*/
const NotFoundError = createHttpError(HttpStatus.NOT_FOUND);
/**
* Represents an UnAuthorized HTTP error (401).
* @extends {HttpError}
*/
const UnAuthorizedError = createHttpError(HttpStatus.UNAUTHORIZED);
/**
* Represents an Internal Server Error HTTP error (500).
* @extends {HttpError}
*/
const InternalServerError = createHttpError(HttpStatus.INTERNAL_SERVER_ERROR);
/**
* Represents an Content Too Larger Error HTTP error (413).
* @extends {HttpError}
*/
const ContentTooLargeError = createHttpError(HttpStatus.PAYLOAD_TOO_LARGE);
//#endregion
export { BadRequestError, ConflictError, ContentTooLargeError, ForbiddenError, HttpError, InternalServerError, NotFoundError, UnAuthorizedError, createHttpError };