Keep error classes across links

Error responses now carry the registered name of the thrown error's
class, and the requester rejects with an instance of that class instead
of a generic RequestError. Error classes are registered like message
classes, and plugins list their own in `errors`.

RequestError is replaced by a hierarchy following the HTTP status codes:
ClientError (ValidationError, ForbiddenError, NotFoundError,
TimeoutError, ConflictError) and ServerError (InternalServerError).
PermissionError is PermissionDeniedError and the config errors
InvalidValue, InvalidField and InvalidAccess gain an Error suffix.

Link logs only errors whose class is not registered. These arrive on the
other side as InternalServerError with the original message and stack,
so an error forwarded through the controller is logged once, where it
was thrown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bbassieandClaude Opus 5.5 committed 2026-10-27 22:03:13 +00:00
1 parent ffe82f81d8
commit 1c7c00b033
37 files changed
+589 -310

No files matched your search

+31 -62
View File
@@ -9,43 +9,12 @@ import * as libSchema from "../schema.js";
import { StringEnum } from "../data/composites.js";
import { safeOutputFile } from "../file_ops.js";
import * as validators from "./validators.js";
import { RequestError } from "../errors.js";
import { InvalidAccessError, InvalidFieldError, InvalidValueError } from "../errors.js";
import type { SyncHook } from "../SyncHook.js";
const ConfigLocation = StringEnum(["controller", "host", "control"]);
export type ConfigLocation = Static<typeof ConfigLocation>;
/**
* Invalid Access exception
*
* Exception class for when an access attempt is made to a field that
* does not permitt this access is done.
*
* @extends Error
*/
export class InvalidAccess extends RequestError { };
/**
* Invalid Value exception
*
* Exception class for when invalid values are attempted to be set on a
* field.
*
* @extends Error
*/
export class InvalidValue extends RequestError { };
/**
* Invalid Field exception
*
* Exception class for when a group or field that does not exist is
* attempted to be accessed.
*
* @extends Error
*/
export class InvalidField extends RequestError { };
const OldConfigGroupSchema = Type.Object({
"name": Type.String(),
"fields": Type.Record(Type.String(), Type.Unknown()),
@@ -368,7 +337,7 @@ export class Config<
* @param name - Name of the field being validated.
* @param def - Definition describing the field type and constraints.
* @param value - Value to validate and coerce.
* @throws {InvalidValue} if the value cannot be coerced to the correct type
* @throws {InvalidValueError} if the value cannot be coerced to the correct type
* @returns The validated and coerced value.
* @private
*/
@@ -380,7 +349,7 @@ export class Config<
// If def is an enum then it must be a value within it
if (def.enum && !def.enum.includes(value)) {
throw new InvalidValue(`Expected one of [${def.enum.join(", ")}], not ${value}`);
throw new InvalidValueError(`Expected one of [${def.enum.join(", ")}], not ${value}`);
}
// If it is a string, then attempt to coerce it
@@ -402,7 +371,7 @@ export class Config<
try {
value = JSON.parse(value);
} catch (err: any) {
throw new InvalidValue(`Error parsing value for ${name}: ${err.message}`);
throw new InvalidValueError(`Error parsing value for ${name}: ${err.message}`);
}
}
}
@@ -410,12 +379,12 @@ export class Config<
// Check if it is allowed to be null
if (value === null) {
if (!def.optional) {
throw new InvalidValue(`Field ${name} cannot be null`);
throw new InvalidValueError(`Field ${name} cannot be null`);
}
// Check if is the correct type
} else if (basicType(value) !== def.type) {
throw new InvalidValue(`Expected type of ${name} to be ${def.type}, not ${basicType(value)}`);
throw new InvalidValueError(`Expected type of ${name} to be ${def.type}, not ${basicType(value)}`);
}
return value as FieldType<T["type"]>;
@@ -429,7 +398,7 @@ export class Config<
* @param location - location to check access for.
* @param mode - type of access to check for.
* @param error - throw on failure to pass check.
* @throws {InvalidAccess}
* @throws {InvalidAccessError}
* if access is not granted and error is true.
* @returns true if access is granted
* @private
@@ -448,7 +417,7 @@ export class Config<
)
) {
if (error) {
throw new InvalidAccess(`Field '${name}' is not accessible from ${location}`);
throw new InvalidAccessError(`Field '${name}' is not accessible from ${location}`);
} else {
return false;
}
@@ -648,7 +617,7 @@ export class Config<
}
let def = this.constructor.fieldDefinitions[name];
if (!def) {
throw new InvalidField(`No field named '${name}'`);
throw new InvalidFieldError(`No field named '${name}'`);
}
return this._checkAccess(name, def, location, mode, false);
}
@@ -663,7 +632,7 @@ export class Config<
get<Field extends keyof Fields & string>(name: Field, remote = this.location) {
let def = this.constructor.fieldDefinitions[name];
if (!def) {
throw new InvalidField(`No field named '${name}'`);
throw new InvalidFieldError(`No field named '${name}'`);
}
// If remote access is requested require it to be able to read the field
if (remote !== this.location) {
@@ -675,7 +644,7 @@ export class Config<
!this._checkAccess(name, def, this.location, ConfigAccess.write, false)
&& !this._checkAccess(name, def, this.location, ConfigAccess.read, false)
) {
throw new InvalidAccess(`Field '${name}' is not accessible from ${this.location}`);
throw new InvalidAccessError(`Field '${name}' is not accessible from ${this.location}`);
}
return this.fields[name];
@@ -690,13 +659,13 @@ export class Config<
* @param name - Name of field to set.
* @param newValue - Value to set for field.
* @param remote - Location this field is being set from.
* @throws {InvalidField} if field is not defined.
* @throws {InvalidValue} if value is not allowed for the field.
* @throws {InvalidFieldError} if field is not defined.
* @throws {InvalidValueError} if value is not allowed for the field.
*/
set<Field extends keyof Fields & string>(name: Field, newValue: Fields[Field], remote = this.location) {
const def = this.constructor.fieldDefinitions[name];
if (!def) {
throw new InvalidField(`No field named '${name}'`);
throw new InvalidFieldError(`No field named '${name}'`);
}
this._checkAccess(name, def, remote, ConfigAccess.write, true);
@@ -714,7 +683,7 @@ export class Config<
try {
def.validator(value, this);
} catch (err: any) {
throw new InvalidValue(`Failed validation of ${name}: ${err.message}`);
throw new InvalidValueError(`Failed validation of ${name}: ${err.message}`);
}
}
} finally {
@@ -732,7 +701,7 @@ export class Config<
try {
dependent.def.validator(this.get(dependent.name as any, remote), this.staging);
} catch (err: any) {
throw new InvalidValue(`Failed validation of dependent ${dependent.name}: ${err.message}`);
throw new InvalidValueError(`Failed validation of dependent ${dependent.name}: ${err.message}`);
}
}
} finally {
@@ -753,8 +722,8 @@ export class Config<
* @param prop - Name of property to set on field.
* @param value - the value to set the property to.
* @param remote - Location this property is being set from
* @throws {InvalidField} if field is not defined.
* @throws {InvalidValue} if field is not an object.
* @throws {InvalidFieldError} if field is not defined.
* @throws {InvalidValueError} if field is not an object.
*/
setProp<Field extends keyof Fields & string>(
name: Field,
@@ -764,7 +733,7 @@ export class Config<
) {
let def = this.constructor.fieldDefinitions[name];
if (!def) {
throw new InvalidField(`No field named '${name}'`);
throw new InvalidFieldError(`No field named '${name}'`);
}
this._checkAccess(name, def, remote, ConfigAccess.write, true);
@@ -773,7 +742,7 @@ export class Config<
}
if (def.type !== "object") {
throw new InvalidValue(`Cannot set property on non-object field '${name}'`);
throw new InvalidValueError(`Cannot set property on non-object field '${name}'`);
}
let prev = this.fields[name] as Record<string, unknown>;
@@ -793,7 +762,7 @@ export class Config<
try {
def.validator(updated, this);
} catch (err: any) {
throw new InvalidValue(`Failed validation of ${name}: ${err.message}`);
throw new InvalidValueError(`Failed validation of ${name}: ${err.message}`);
}
}
} finally {
@@ -811,7 +780,7 @@ export class Config<
try {
dependent.def.validator(this.get(dependent.name as any, remote), this.staging);
} catch (err: any) {
throw new InvalidValue(`Failed validation of dependent ${dependent.name}: ${err.message}`);
throw new InvalidValueError(`Failed validation of dependent ${dependent.name}: ${err.message}`);
}
}
} finally {
@@ -829,8 +798,8 @@ export class Config<
* @param name - Name of field to set.
* @param newValue - Value to set for field.
* @param remote - Location this field is being set from.
* @throws {InvalidField} if field is not defined.
* @throws {InvalidValue} if value is not allowed for the field.
* @throws {InvalidFieldError} if field is not defined.
* @throws {InvalidValueError} if value is not allowed for the field.
*/
stage<Field extends keyof Fields & string>(name: Field, newValue: Fields[Field], remote = this.location) {
if (this._readonly) {
@@ -839,7 +808,7 @@ export class Config<
const def = this.constructor.fieldDefinitions[name];
if (!def) {
throw new InvalidField(`No field named '${name}'`);
throw new InvalidFieldError(`No field named '${name}'`);
}
this._checkAccess(name, def, remote, ConfigAccess.write, true);
@@ -859,8 +828,8 @@ export class Config<
* @param prop - Name of property to set on field.
* @param value - the value to set the property to.
* @param remote - Location this property is being set from
* @throws {InvalidField} if field is not defined.
* @throws {InvalidValue} if field is not an object.
* @throws {InvalidFieldError} if field is not defined.
* @throws {InvalidValueError} if field is not an object.
*/
stageProp<Field extends keyof Fields & string>(
name: Field,
@@ -874,7 +843,7 @@ export class Config<
const def = this.constructor.fieldDefinitions[name];
if (!def) {
throw new InvalidField(`No field named '${name}'`);
throw new InvalidFieldError(`No field named '${name}'`);
}
this._checkAccess(name, def, remote, ConfigAccess.write, true);
@@ -883,7 +852,7 @@ export class Config<
}
if (def.type !== "object") {
throw new InvalidValue(`Cannot set property on non-object field '${name}'`);
throw new InvalidValueError(`Cannot set property on non-object field '${name}'`);
}
const prev = this.staging.get(name) as Record<string, unknown>;
@@ -901,7 +870,7 @@ export class Config<
/**
* Commit all changes in stating after they have been validated.
*
* @throws {InvalidValue} if a value is not allowed for its field.
* @throws {InvalidValueError} if a value is not allowed for its field.
*/
commitStaging() {
if (this._readonly) {
@@ -923,7 +892,7 @@ export class Config<
try {
fieldDef.validator(config.fields[fieldName as keyof Fields], config);
} catch (err: any) {
throw new InvalidValue(`Failed validation of ${fieldName}: ${err.message}`);
throw new InvalidValueError(`Failed validation of ${fieldName}: ${err.message}`);
}
}
}
+1 -1
View File
@@ -162,7 +162,7 @@ export interface IUser extends UserDetails {
*
* @param permission - The permission to check for.
* @throws {Error} If the given permission does not exist.
* @throws {libErrors.PermissionError} if the user does noh have the given permission.
* @throws {libErrors.PermissionDeniedError} if the user does noh have the given permission.
*/
checkPermission(permission: PermissionName): void
}
+3 -3
View File
@@ -2,7 +2,7 @@ import { Type, Static } from "@sinclair/typebox";
import UserDetails, { IUser } from "./UserDetails.js";
import { StringEnum, jsonArray, plainJson } from "./composites.js";
import { MessageRequest } from "./messages_core.js";
import { PermissionError } from "../errors.js";
import { ValidationError } from "../errors.js";
export class UserGetRequest {
declare ["constructor"]: typeof UserGetRequest;
@@ -277,9 +277,9 @@ export class UserBulkImportRequest {
user.checkPermission("core.user.set_whitelisted");
break;
default:
// Unvalidated input during permission check: deny, don't throw a bare Error
// Unvalidated input during permission check: reject, don't throw a bare Error
// @ts-expect-error Unreachable
throw new PermissionError(`Unknown import / restore type: ${data.importType}`);
throw new ValidationError(`Unknown import / restore type: ${data.importType}`);
}
}
}
+61 -25
View File
@@ -18,40 +18,76 @@ export class InstallationError extends Error {
}
/**
* Thrown from requests sent when an error occured handling it
* Base class for errors caused by the request, such as invalid input,
* missing permissions or a missing resource. Corresponds to the HTTP 4xx
* range.
*
* Link does not log these as unexpected when a request handler throws them.
*/
export class RequestError extends Error {
constructor(
message: string,
public code = "RequestError",
public stack?: string,
) {
super(message);
}
}
export class ClientError extends Error { }
/**
* Thrown when a permission check fails.
*
* Is a subclass of RequestError to prevent logging stack traces when
* requests fail due to permission denied.
*
* Thrown when the request contains invalid data (HTTP 400)
*/
export class PermissionError extends RequestError {
constructor(
message: string,
code = "PermissionError",
stack?: string,
) {
super(message, code, stack);
}
export class ValidationError extends ClientError { }
}
/**
* Thrown when a config value cannot be used for its field
*/
export class InvalidValueError extends ValidationError { }
/**
* Thrown when a config field does not exist
*/
export class InvalidFieldError extends ValidationError { }
/**
* Thrown when the request is not allowed (HTTP 403)
*/
export class ForbiddenError extends ClientError { }
/**
* Thrown when a permission check fails
*/
export class PermissionDeniedError extends ForbiddenError { }
/**
* Thrown when a config field is not accessible from the current location
*/
export class InvalidAccessError extends ForbiddenError { }
/**
* Thrown when a resource the request refers to does not exist (HTTP 404)
*/
export class NotFoundError extends ClientError { }
/**
* Thrown when an operation for a request timed out (HTTP 408)
*/
export class TimeoutError extends ClientError { }
/**
* Thrown when the request conflicts with the current state, such as an
* instance that is running or a host that is not connected (HTTP 409)
*/
export class ConflictError extends ClientError { }
/**
* Base class for errors caused by the side handling the request.
* Corresponds to the HTTP 5xx range.
*/
export class ServerError extends Error { }
/**
* Received in place of an error response whose class is not registered,
* such as a TypeError thrown by a request handler (HTTP 500)
*/
export class InternalServerError extends ServerError { }
/**
* Signal for messages that fail validation
*/
export class InvalidMessage extends Error {
export class InvalidMessage extends ValidationError {
code = "InvalidMessage";
constructor(
message: string,
+101 -26
View File
@@ -3,7 +3,7 @@ import * as libData from "../data/index.js";
import * as libErrors from "../errors.js";
import { logger } from "../logging.js";
import * as libSchema from "../schema.js";
import { dataClasses } from "./messages.js";
import { dataClasses, errorClasses } from "./messages.js";
import { BaseConnector, WebSocketBaseConnector } from "./connectors.js";
import { strict as assert } from "assert";
import type { PluginNodeEnvInfo, PluginWebpackEnvInfo } from "../plugin.js";
@@ -38,6 +38,12 @@ export interface Event<T> {
}
export type EventClass<T> = Event<T>["constructor"];
export interface ErrorClass {
new (message: string): Error;
name: string;
plugin?: string;
}
export interface RequestEntry {
Request: RequestClass<unknown, unknown>;
name: string,
@@ -156,7 +162,7 @@ export class Link {
return this._pendingRequests.size + this._forwardedRequests.size;
}
_clearPendingRequests(err: Error & { code?: string }) {
_clearPendingRequests(err: Error) {
for (let pending of this._pendingRequests.values()) {
pending.reject(err);
}
@@ -170,9 +176,7 @@ export class Link {
) {
continue;
}
pending.origin.connector.sendResponseError(
new libData.ResponseError(err.message, err.code), pending.src, pending.dst
);
pending.origin.connector.sendResponseError(Link.errorToResponse(err, false), pending.src, pending.dst);
}
this._pendingRequests.clear();
this._forwardedRequests.clear();
@@ -200,10 +204,10 @@ export class Link {
try {
this.validatePermission(permissionMessage, entry); // Somewhat hacky, defined in ControlConnection
} catch (err) {
// A non-PermissionError means the permission check itself is
// A non-ClientError means the permission check itself is
// broken. validatePermission (control connections only) already
// sent a response error, so log and drop instead of crashing.
if (!(err instanceof libErrors.PermissionError)) {
if (!(err instanceof libErrors.ClientError)) {
logger.error(
`Unexpected error checking permission for ${permissionMessage.name}:\n` +
`${(err as Error).stack ?? (err as Error).message}`
@@ -280,7 +284,7 @@ export class Link {
this.validateIngress(message);
} catch (err: any) {
if (message.type === "request") {
this.connector.sendResponseError(new libData.ResponseError(err.message, err.code), message.src);
this.connector.sendResponseError(Link.errorToResponse(err, false), message.src);
}
throw err;
}
@@ -290,17 +294,17 @@ export class Link {
let entry = Link._requestsByName.get(message.name);
if (!entry) {
let err = new libErrors.InvalidMessage(`Unrecognized request ${message.name}`);
this.connector.sendResponseError(new libData.ResponseError(err.message, err.code), message.src);
this.connector.sendResponseError(Link.errorToResponse(err, false), message.src);
throw err;
}
if (!entry.allowedSrcTypes.has(message.src.type)) {
let err = new libErrors.InvalidMessage(`Source ${message.src} is not allowed for ${message.name}`);
this.connector.sendResponseError(new libData.ResponseError(err.message, err.code), message.src);
this.connector.sendResponseError(Link.errorToResponse(err, false), message.src);
throw err;
}
if (!entry.allowedDstTypes.has(message.dst.type)) {
let err = new libErrors.InvalidMessage(`Destination ${message.dst} is not allowed for ${message.name}`);
this.connector.sendResponseError(new libData.ResponseError(err.message, err.code), message.src);
this.connector.sendResponseError(Link.errorToResponse(err, false), message.src);
throw err;
}
return entry;
@@ -344,7 +348,7 @@ export class Link {
*
* @param message - Message to check.
* @param entry - Request or Event entry for this Message.
* @throws {libErrors.PermissionError} if unauthorized.
* @throws {libErrors.PermissionDeniedError} if unauthorized.
*/
validatePermission(message: libData.MessageRequest | libData.MessageEvent, entry: RequestEntry | EventEntry) { }
@@ -356,7 +360,7 @@ export class Link {
);
if (message.type === "request") {
this.connector.sendResponseError(
new libData.ResponseError(err.message, err.code), (message as libData.MessageRequest).src
Link.errorToResponse(err, false), (message as libData.MessageRequest).src
);
}
throw err;
@@ -399,13 +403,7 @@ export class Link {
try {
response = handler(entry.requestFromJSON(message.data), message.src, message.dst);
} catch (err: any) {
if (err.errors) {
logger.error(JSON.stringify(err.errors, null, "\t"));
}
this.connector.sendResponseError(
new libData.ResponseError(err.message, err.code, err.stack), message.src
);
return;
response = Promise.reject(err);
}
if (!(response instanceof Promise)) {
@@ -424,19 +422,17 @@ export class Link {
this.connector.sendResponse(result, message.src, spoofedSrc);
}
).catch(
(err: Error & { code?: string }) => {
(err: Error) => {
if (err instanceof libErrors.InvalidMessage) {
logger.error(err.message);
if (err.errors) {
logger.error(JSON.stringify(err.errors, null, "\t"));
}
} else if (!(err instanceof libErrors.RequestError)) {
} else if (Link.errorName(err) === undefined) {
logger.error(`Unexpected error responding to ${message.name}:\n${err.stack}`);
}
try {
this.connector.sendResponseError(
new libData.ResponseError(err.message, err.code, err.stack), message.src, spoofedSrc
);
this.connector.sendResponseError(Link.errorToResponse(err), message.src, spoofedSrc);
} catch (subErr: any) {
logger.error(`Unexpected error sending error response for ${message.name}:\n${subErr.stack}`);
}
@@ -474,7 +470,7 @@ export class Link {
}
this._pendingRequests.delete(message.dst.requestId!);
pending.reject(new libErrors.RequestError(message.data.message, message.data.code, message.data.stack));
pending.reject(Link.errorFromResponse(message.data));
}
_processEvent(message: libData.MessageEvent, entry: EventEntry) {
@@ -823,11 +819,81 @@ export class Link {
this._eventsByName.set(name, entry);
this._eventsByClass.set(Event as EventClass<unknown>, entry);
}
static _errorsByName = new Map<string, ErrorClass>();
static _errorNamesByClass = new Map<ErrorClass, string>();
/**
* Register an error class to be sent and received over links
*
* Error responses carry the registered name of the thrown error and the
* receiving side rejects the request with an instance of the same class.
*
* @param Class - Error class, must take the message as the first
* constructor argument.
*/
static registerError(Class: ErrorClass) {
const name = Class.plugin ? `${Class.plugin}:${Class.name}` : Class.name;
if (this._errorsByName.has(name)) {
throw new Error(`Error ${name} is already registered`);
}
this._errorsByName.set(name, Class);
this._errorNamesByClass.set(Class, name);
}
/**
* Registered name of the closest registered class of an error
*
* @param err - Error to look up.
* @returns name or undefined if no class in its prototype chain is registered.
*/
static errorName(err: Error) {
for (let proto = Object.getPrototypeOf(err); proto; proto = Object.getPrototypeOf(proto)) {
const name = this._errorNamesByClass.get(proto.constructor);
if (name) {
return name;
}
}
return undefined;
}
/**
* Convert an error into the data of an error response
*
* Errors with no registered class are sent as InternalServerError.
*
* @param err - Error to convert.
* @param withStack - Include the stack trace of the error.
*/
static errorToResponse(err: Error, withStack = true) {
return new libData.ResponseError(
err.message, this.errorName(err) ?? "InternalServerError", withStack ? err.stack : undefined
);
}
/**
* Convert the data of an error response back into an error
*
* @param response - Received error response data.
* @returns instance of the registered class, or InternalServerError if
* the class is not registered on this side.
*/
static errorFromResponse(response: libData.ResponseError) {
const Class = response.code && this._errorsByName.get(response.code) || libErrors.InternalServerError;
const err = new Class(response.message);
if (response.stack !== undefined) {
err.stack = response.stack;
}
return err;
}
}
for (let Class of dataClasses) {
Link.register(Class as RequestClass<unknown, unknown>);
}
for (let Class of errorClasses) {
Link.registerError(Class);
}
export function registerPluginMessages(pluginInfos: PluginNodeEnvInfo[]|PluginWebpackEnvInfo[]) {
for (let pluginInfo of pluginInfos) {
@@ -840,5 +906,14 @@ export function registerPluginMessages(pluginInfos: PluginNodeEnvInfo[]|PluginWe
}
Link.register(Class);
}
for (let Class of pluginInfo.errors || []) {
if (Class.plugin !== pluginInfo.name) {
throw new Error(
`Expected error ${Class.name} from ${pluginInfo.name} to have a static ` +
`plugin property set to "${pluginInfo.name}"`
);
}
Link.registerError(Class);
}
}
}
+24 -1
View File
@@ -8,7 +8,8 @@ import * as role from "../data/messages_role.js";
import * as note from "../data/messages_note.js";
import * as plugin from "../data/messages_plugin.js";
import * as subscriptions from "../subscriptions.js";
import type { RequestClass, EventClass } from "./link.js";
import * as errors from "../errors.js";
import type { RequestClass, EventClass, ErrorClass } from "./link.js";
/**
* Event and Request payloads registered with the Link class. Used to decode
@@ -151,3 +152,25 @@ export const dataClasses: (RequestClass<unknown, unknown> | EventClass<unknown>)
plugin.PluginLatestVersionsRequest,
plugin.UpdateAllRequest,
];
/**
* Error classes registered with the Link class. Used to send errors thrown
* by request handlers back as instances of the same class.
* @internal
*/
export const errorClasses: ErrorClass[] = [
errors.ClientError,
errors.ValidationError,
errors.InvalidValueError,
errors.InvalidFieldError,
errors.ForbiddenError,
errors.PermissionDeniedError,
errors.InvalidAccessError,
errors.NotFoundError,
errors.TimeoutError,
errors.ConflictError,
errors.ServerError,
errors.InternalServerError,
errors.InvalidMessage,
errors.SessionLost,
];
+2
View File
@@ -8,6 +8,7 @@ import type { ConfigSchema, FieldDefinition } from "./config/index.js";
import type { PermissionDefinition } from "./permissions.js";
import type { PlayerStats, Role } from "./data/index.js";
import type { SyncHook } from "./SyncHook.js";
import type { ErrorClass } from "./link/index.js";
export const PluginFeatureFlags = [
/** The plugin requires module code to be patched into the save */
@@ -42,6 +43,7 @@ export type PluginDeclaration = {
features?: (typeof PluginFeatureFlags)[number][];
messages?: any[];
errors?: ErrorClass[];
permissions?: PermissionDefinition[];
routes?: string[];
}
+6 -6
View File
@@ -2,7 +2,7 @@ import util from "util";
import path from "path";
import { exec } from "child_process";
import { logger } from "./logging.js";
import { RequestError } from "./errors.js";
import { ConflictError, NotFoundError, UnavailableError } from "./errors.js";
import type { PluginNodeEnvInfo } from "./plugin.js";
import { isNonRegistryPackage } from "./load_plugin_list.js";
import { LockFile, LockFileExistsError, LockFileRecoveryError } from "./LockFile.js";
@@ -31,7 +31,7 @@ let operationInProgress = false;
async function logExec(cmd: string, check?: () => Promise<void>) {
// Checked and set before the first await so concurrent calls in this process can't interleave
if (operationInProgress) {
throw new RequestError(operationInProgressMessage);
throw new ConflictError(operationInProgressMessage);
}
operationInProgress = true;
const lockPath = path.resolve("npm-operation.lock");
@@ -43,13 +43,13 @@ async function logExec(cmd: string, check?: () => Promise<void>) {
await lock.acquire();
} catch (err) {
if (err instanceof LockFileRecoveryError) {
throw new RequestError(err.message);
throw new UnavailableError(err.message);
}
if (!(err instanceof LockFileExistsError)) {
throw err;
}
const holder = await lock.holderPid();
throw new RequestError(
throw new ConflictError(
`${operationInProgressMessage}${holder ? ` (${lockPath} is held by process ${holder})` : ""}`
);
}
@@ -90,7 +90,7 @@ export async function handleUpdateAll(corePackage: string, pluginInfos: PluginNo
/** Throws if the dependency by this name is a path, git, url or alias that installing by name would replace */
async function checkNotLocalDependency(name: string) {
if (await isNonRegistryPackage(name)) {
throw new RequestError(`${name} is not installed from npm on this machine`);
throw new ConflictError(`${name} is not installed from npm on this machine`);
}
}
@@ -98,7 +98,7 @@ export async function handlePluginUpdate(pluginName: string, pluginInfos: Plugin
// Optionally pinned to a version as name@version to update past the range in package.json
const { name, version } = parsePackageSpec(pluginName);
if (!pluginInfos.some(plugin => plugin.npmPackage === name)) {
throw new RequestError(`Plugin ${name} is not installed on this machine`);
throw new NotFoundError(`Plugin ${name} is not installed on this machine`);
}
if (version === undefined) {
+3 -2
View File
@@ -9,6 +9,7 @@ import { spawn } from "child_process";
import { loadPluginList } from "./load_plugin_list.js";
import * as libConfig from "./config/index.js";
import * as libFileOps from "./file_ops.js";
import { InvalidFieldError, InvalidValueError } from "./errors.js";
import { logger } from "./logging.js";
import * as libHelpers from "./helpers.js";
import { LockFile } from "./LockFile.js";
@@ -271,7 +272,7 @@ export async function handleConfigCommand(
try {
print(instance.get(args.field as string));
} catch (err) {
if (err instanceof libConfig.InvalidField) {
if (err instanceof InvalidFieldError) {
logger.error(err.message);
} else {
throw err;
@@ -292,7 +293,7 @@ export async function handleConfigCommand(
instance.set(args.field as string, args.value);
await instance.save();
} catch (err) {
if (err instanceof libConfig.InvalidField || err instanceof libConfig.InvalidValue) {
if (err instanceof InvalidFieldError || err instanceof InvalidValueError) {
logger.error(err.message);
} else {
throw err;
+3 -3
View File
@@ -3,7 +3,7 @@ import { Link, Event, EventClass, RequestHandler, WebSocketBaseConnector } from
import { Address, MessageRequest, IUser, JsonBoolean, StringEnum } from "./data/index.js";
import isDeepStrictEqual from "#is_deep_strict_equal";
import type { PermissionName } from "./permissions.js";
import { RequestError } from "./errors.js";
import { SessionLost, ValidationError } from "./errors.js";
import { logger } from "./logging.js";
export type SubscriptionRequestHandler<T> = RequestHandler<SubscriptionRequest, Event<T> | null>;
@@ -351,7 +351,7 @@ export class SubscriptionController {
}
}
if (count > this._maxFilters) {
throw new RequestError(`Subscription exceeds the limit of ${this._maxFilters} filters`);
throw new ValidationError(`Subscription exceeds the limit of ${this._maxFilters} filters`);
}
}
@@ -685,7 +685,7 @@ export class EventSubscriber<E, S = null> {
this._notify(null);
}
} catch (err: any) {
if (!(err instanceof RequestError) || err.code !== "SessionLost") {
if (!(err instanceof SessionLost)) {
logger.error(`Unexpected error updating ${entry.name} subscription:\n${err.stack}`);
}
if (err instanceof Error) {