Skip to content

SerialError

Legacy v1 docs

v1 is on security fixes only. See v2 docs for the current release.

SerialError is a structured error class that wraps serial communication failures with a typed code and optional context.

typescript
import { SerialError, SerialErrorCode } from "webserial-core";

Constructor

typescript
new SerialError(
  message: string,
  code?: SerialErrorCode,
  context?: Record<string, unknown>
)
ParameterDefaultDescription
messageHuman-readable description
codeSerialErrorCode.UNKNOWN_ERRORError category from SerialErrorCode
contextundefinedExtra key/value information (port name, baud rate, etc.)

SerialErrorCode enum

ValueDescription
CONNECTION_FAILEDCould not open the serial port
DISCONNECTION_FAILEDPort failed to close cleanly
WRITE_FAILEDWriting bytes to the port failed
READ_FAILEDReading bytes from the port failed
TIMEOUTNo response received within the allotted time
PORT_NOT_FOUNDSerial port no longer found / unplugged
PERMISSION_DENIEDBrowser denied access to the port
DEVICE_NOT_SUPPORTEDDevice type is not supported
INVALID_CONFIGURATIONBad constructor options
SOCKET_ERRORSocket.io communication error
UNKNOWN_ERRORGeneral uncategorised error

Properties

PropertyTypeDescription
namestringAlways "SerialError"
messagestringHuman-readable message
codeSerialErrorCodeError category
contextRecord<string, unknown> | undefinedOptional extra context
timestampDateWhen the error was created
stackstring | undefinedV8 stack trace

Methods

toJSON()

Returns a plain object suitable for logging or serialisation.

typescript
toJSON(): Record<string, unknown>
javascript
const err = new SerialError(
  "Failed to connect",
  SerialErrorCode.CONNECTION_FAILED,
  { baudRate: 9600 },
);

console.log(err.toJSON());
// {
//   name: "SerialError",
//   message: "Failed to connect",
//   code: "CONNECTION_FAILED",
//   context: { baudRate: 9600 },
//   timestamp: "2024-01-15T10:30:00.000Z",
//   stack: "..."
// }

toString()

Returns a formatted single-line string.

typescript
toString(): string
// "SerialError [CONNECTION_FAILED]: Failed to connect | Context: {"baudRate":9600}"

Usage

javascript
arduino.on("serial:error", (event) => {
  const err = event.detail;
  if (err instanceof SerialError) {
    console.error(`[${err.code}] ${err.message}`, err.context);
  } else {
    console.error(err);
  }
});

Released under the MIT License.