Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## [3.1.1] - 2025-02-21

- Improved error messages and logging.

## [3.1.0] - 2024-12-17

- Fixed downloading old submissions for C# exercises
Expand Down
2 changes: 1 addition & 1 deletion backend/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
"compilerOptions": {
"esModuleInterop": true,
"module": "commonjs",
"target": "ES6"
"target": "ES2022"
}
}
4 changes: 2 additions & 2 deletions bin/validateRelease.sh
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ then
fi

# Make sure that the package-lock.json version also matches
packageLockVersion=$(grep -Eo '"version":.+$' package-lock.json)
packageLockVersion=$(grep -Eom 1 '"version":.+$' package-lock.json)
if [[ ! $packageLockVersion =~ '"version": "'$tagVersion'",' ]]
then
echo "Error: The version in package-lock.json '${packageVersion}' doesn't match with the tag '${tagVersion}'. Run 'npm i --package-lock-only'}"
echo "Error: The version in package-lock.json '${packageLockVersion}' doesn't match with the tag '${tagVersion}'. Run \`npm i --package-lock-only\`."
exitCode=1
fi

Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "test-my-code",
"displayName": "TestMyCode",
"version": "3.1.0",
"version": "3.1.1",
"description": "TestMyCode extension for Visual Studio Code",
"categories": [
"Education",
Expand Down
4 changes: 2 additions & 2 deletions playwright/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
"compilerOptions": {
"noEmit": true,
"module": "commonjs",
"target": "es6",
"lib": ["es6"],
"target": "ES2022",
"lib": ["ES2022"],
"sourceMap": true,
"rootDir": ".",
"strict": true
Expand Down
104 changes: 101 additions & 3 deletions shared/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
*/

import { Uri } from "vscode";
import * as util from "node:util";

import { Course, Organization, RunResult, SubmissionFinished } from "./langsSchema";
import { createIs } from "typia";

/**
* Contains the state of the webview.
Expand Down Expand Up @@ -529,9 +531,105 @@ export function assertUnreachable(x: never): never {
*/
export class BaseError extends Error {
public readonly name: string = "Base Error";
public details: string;
constructor(message?: string, details?: string) {
public details?: string;
public cause?: NodeJS.ErrnoException | string;
public stack?: string;

// possible fields from ErrnoException
public errno?: number;
public code?: string;
public path?: string;
public syscall?: string;

constructor(err: unknown);
constructor(err: Error, details?: string);
constructor(message?: string, details?: string);

constructor(err: unknown, details?: string) {
let message = "";
let stack = "";
let cause: NodeJS.ErrnoException | string = "";

let errno: number | undefined = undefined;
let code: string | undefined = undefined;
let path: string | undefined = undefined;
let syscall: string | undefined = undefined;

// simple check first...
if (typeof err === "string") {
message = err;
} else if (util.types.isNativeError(err)) {
// deal with regular error stuff first
message = err.message;
if (err.stack) {
stack = err.stack;
}

// also check for special NodeJS error
if (createIs<NodeJS.ErrnoException>()(err)) {
// nodejs error with error code
errno = err.errno;
code = err.code;
path = err.path;
syscall = err.syscall;
}

if (err.cause) {
// same checks for cause
if (
util.types.isNativeError(err.cause) &&
createIs<NodeJS.ErrnoException>()(err.cause)
) {
cause = err.cause;
} else {
cause = err.cause.toString();
}
}
} else {
// it's expected that this function is only called with
// strings or error objects. but since errors are often "unknown"
// in catch statements etc., this function accepts unknown types
// and thus we'll handle them here just in case
message = `Unexpected error ${err} (${typeof err})`;
}

super(message);
this.details = details ?? "";
this.details = details;
if (stack) {
this.stack = stack;
}
if (cause) {
this.cause = cause;
}

// errno fields
this.errno = errno;
this.code = code;
this.path = path;
this.syscall = syscall;
}

public toString(): string {
let errorMessage = "";
if (this.errno) {
errorMessage += `[${this.errno}] `;
}
if (this.code) {
errorMessage += `(${this.code}) `;
}
if (this.syscall) {
errorMessage += `\`${this.syscall}\` `;
}
if (this.path) {
errorMessage += `@${this.path} `;
}
errorMessage += `${this.name}: ${this.message}.`;
if (this.details) {
errorMessage += ` ${this.details}.`;
}
if (this.cause) {
errorMessage += ` Caused by: ${this.cause}.`;
}
return errorMessage;
}
}
2 changes: 1 addition & 1 deletion src/actions/checkForExerciseUpdates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export async function checkForExerciseUpdates(
): Promise<Result<OutdatedExercise[], Error>> {
const { tmc, userData } = actionContext;
const forceRefresh = options?.forceRefresh ?? false;
Logger.info(`Checking for exercise updates, forced update: ${forceRefresh}`);
Logger.info("Checking for exercise updates, forced update:", forceRefresh);

const checkUpdatesResult = await tmc.checkExerciseUpdates({ forceRefresh });
if (checkUpdatesResult.err) {
Expand Down
2 changes: 1 addition & 1 deletion src/actions/downloadNewExercisesForCourse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export async function downloadNewExercisesForCourse(
): Promise<Result<void, Error>> {
const { userData } = actionContext;
const course = userData.getCourse(courseId);
Logger.info(`Downloading new exercises for course: ${course.title}`);
Logger.info("Downloading new exercises for course:", course.title);

const postNewExercises = async (exerciseIds: number[]): Promise<void> =>
await TmcPanel.postMessage({
Expand Down
2 changes: 1 addition & 1 deletion src/actions/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ export async function submitExercise(

if (submissionResult.err) {
if (submissionResult.val instanceof BottleneckError) {
Logger.warn(`Submission was cancelled: ${submissionResult.val.message}.`);
Logger.warn("Submission was cancelled:", submissionResult.val);
return Ok.EMPTY;
}
TmcPanel.postMessage({
Expand Down
4 changes: 2 additions & 2 deletions src/api/workspaceManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ export default class WorkspaceManager implements vscode.Disposable {
const tmcWorkspaceFilePath = this._resources.getWorkspaceFilePath(courseName);
if (!fs.existsSync(tmcWorkspaceFilePath)) {
fs.writeFileSync(tmcWorkspaceFilePath, JSON.stringify(WORKSPACE_SETTINGS));
Logger.info(`Created tmc workspace file at ${tmcWorkspaceFilePath}`);
Logger.info("Created tmc workspace file at", tmcWorkspaceFilePath);
}
}

Expand Down Expand Up @@ -408,7 +408,7 @@ export default class WorkspaceManager implements vscode.Disposable {

// TODO: Check that document is a valid exercise
const isCode = this._resources.editorKind === EditorKind.Code;
Logger.debug("Text document languageId " + e.languageId);
Logger.debug("Text document languageId", e.languageId);
switch (e.languageId) {
case "c":
case "cpp":
Expand Down
2 changes: 1 addition & 1 deletion src/commands/submitExercise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export async function submitExercise(
const result = await actions.submitExercise(context, actionContext, exercise);
if (result.err) {
if (result.val instanceof BottleneckError) {
Logger.warn(`Submission was cancelled: ${result.val.message}.`);
Logger.warn("Submission was cancelled:", result.val);
return;
}

Expand Down
10 changes: 5 additions & 5 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export async function activate(context: vscode.ExtensionContext): Promise<void>
try {
await activateInner(context);
} catch (e) {
Logger.error(`Error during initialization: ${e}`);
Logger.error("Error during initialization:", e);
vscode.window.showErrorMessage(`TestMyCode initialization failed: ${e}`);
Logger.show();
}
Expand All @@ -69,7 +69,7 @@ async function activateInner(context: vscode.ExtensionContext): Promise<void> {

const authenticatedResult = await tmc.isAuthenticated({ timeout: 15000 });
if (authenticatedResult.err) {
Logger.error("Failed to check if authenticated:", authenticatedResult.val.message);
Logger.error("Failed to check if authenticated:", authenticatedResult.val);
throwFatalError(authenticatedResult.val, cliFolder);
}

Expand All @@ -86,7 +86,7 @@ async function activateInner(context: vscode.ExtensionContext): Promise<void> {
);
if (migrationResult.err) {
if (migrationResult.val instanceof HaltForReloadError) {
Logger.warn("Extension expected to restart");
Logger.warn("Extension expected to restart", migrationResult.val);
return;
}

Expand All @@ -111,7 +111,7 @@ async function activateInner(context: vscode.ExtensionContext): Promise<void> {
workspaceFileFolder,
);
if (resourcesResult.err) {
Logger.error("Resource initialization failed: ", resourcesResult.val);
Logger.error("Resource initialization failed:", resourcesResult.val);
throwFatalError(resourcesResult.val, cliFolder);
}

Expand Down Expand Up @@ -194,7 +194,7 @@ async function activateInner(context: vscode.ExtensionContext): Promise<void> {
maintenanceInterval = setInterval(async () => {
const authenticated = await tmc.isAuthenticated();
if (authenticated.err) {
Logger.error("Failed to check if authenticated", authenticated.val.message);
Logger.error("Failed to check if authenticated", authenticated.val);
} else if (authenticated.val) {
vscode.commands.executeCommand("tmc.updateExercises", "silent");
checkForCourseUpdates(actionContext);
Expand Down
55 changes: 50 additions & 5 deletions src/utilities/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { env } from "process";
import { OutputChannel, Uri, window } from "vscode";

import { DEBUG_MODE, OUTPUT_CHANNEL_NAME } from "../config/constants";
import { BaseError } from "../shared/shared";

export enum LogLevel {
None = "none",
Expand Down Expand Up @@ -69,7 +70,7 @@ export class Logger {

static toLoggable(p: unknown): string {
if (p instanceof Error) {
return `${p.name} \u2014 ${p.message} \u2014 ${p.stack}`;
return formatError(p, this._level);
}
if (typeof p !== "object") {
return String(p);
Expand All @@ -96,21 +97,22 @@ export class Logger {
private static _log(level: ConsoleLogLevel, ...params: unknown[]): void {
if (DEBUG_MODE) {
// in debug mode, we log to console with the appropriate level
const loggableParams = this._toLoggableParams(params);
switch (level) {
case "DEBUG": {
console.debug(this._timestamp, channel, ...params);
console.debug(this._timestamp, channel, loggableParams);
break;
}
case "INFO": {
console.info(this._timestamp, channel, ...params);
console.info(this._timestamp, channel, loggableParams);
break;
}
case "WARN": {
console.warn(this._timestamp, channel, ...params);
console.warn(this._timestamp, channel, loggableParams);
break;
}
case "ERROR": {
console.error(this._timestamp, channel, ...params);
console.error(this._timestamp, channel, loggableParams);
break;
}
}
Expand Down Expand Up @@ -167,3 +169,46 @@ export class Logger {
return loggableParams.length !== 0 ? loggableParams : "";
}
}

function formatError(error: Error, level: LogLevel): string {
if (error instanceof BaseError) {
let errorMessage = "";
if (error.errno) {
errorMessage += `[${error.errno}] `;
}
if (error.code) {
errorMessage += `(${error.code}) `;
}
if (error.syscall) {
errorMessage += `\`${error.syscall}\` `;
}
if (error.path) {
errorMessage += `@${error.path} `;
}
errorMessage += `${error.name}: ${error.message}.`;
if (error.details) {
errorMessage += ` ${error.details}.`;
}
if (error.cause) {
if (typeof error.cause === "string") {
errorMessage += ` ${error.cause}.`;
} else {
const cause = formatError(error.cause, level);
errorMessage += ` Caused by: {${cause}}.`;
}
}
if (error.stack && level === LogLevel.Verbose) {
errorMessage += `\n<TRACE>\n${error.stack}\n</TRACE>`;
}
return errorMessage;
} else {
let errorMessage = `${error.name}: ${error.message}.`;
if (error.cause) {
errorMessage += ` ${error.cause}.`;
}
if (error.stack && level === LogLevel.Verbose) {
errorMessage += `\n<TRACE>\n${error.stack}\n</TRACE>`;
}
return errorMessage;
}
}
2 changes: 1 addition & 1 deletion src/utilities/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export async function downloadFile(
} catch (error) {
Logger.error(error);
// Typing change from update
return new Err(new ConnectionError("Connection error: " + (error as Error).name));
return new Err(new ConnectionError(error));
}

if (!response.ok) {
Expand Down
2 changes: 1 addition & 1 deletion src/window/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function getActiveEditorExecutablePath(actionContext: ActionContext): str
if (!resource) {
return undefined;
}
Logger.info("Active text document language: " + resource.document.languageId);
Logger.info("Active text document language:", resource.document.languageId);
switch (resource.document.languageId) {
case "python":
return getPythonPath(actionContext, resource.document);
Expand Down
Loading
Loading