Skip to content
This repository has been archived by the owner on Apr 23, 2022. It is now read-only.

Commit

Permalink
Refine error type
Browse files Browse the repository at this point in the history
  • Loading branch information
dilin-MS2 committed Feb 12, 2020
1 parent 0a8d8ef commit edd31c6
Show file tree
Hide file tree
Showing 46 changed files with 482 additions and 286 deletions.
2 changes: 1 addition & 1 deletion src/AzureOperator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export class AzureOperator {
telemetryContext: TelemetryContext
): Promise<void> {
// Azure deploy command can be executed only in local environment
RemoteExtension.ensureLocalBeforeRunCommand(context);
RemoteExtension.ensureLocalBeforeRunCommand("deploy azure project", context);

const iotProject = await constructAndLoadIoTProject(context, channel, telemetryContext);
if (iotProject) {
Expand Down
59 changes: 42 additions & 17 deletions src/DigitalTwin/CodeGeneratorCore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ import { FileUtility } from "../FileUtility";
import { OperationCanceledError } from "../common/Error/OperationCanceledError";
import { Utility } from "./pnp/src/common/utility";
import { OperationFailedError } from "../common/Error/OperationFailedErrors/OperationFailedError";
import { SystemResourceNotFoundError } from "../common/Error/SystemErrors/SystemResourceNotFoundError";
import { TypeNotSupportedError } from "../common/Error/SystemErrors/TypeNotSupportedError";
import { WorkspaceNotOpenError } from "../common/Error/OperationFailedErrors/WorkspaceNotOpenError";

interface CodeGeneratorDownloadLocation {
win32Md5: string;
Expand Down Expand Up @@ -92,9 +95,12 @@ export class CodeGeneratorCore {
channel: vscode.OutputChannel,
telemetryContext: TelemetryContext
): Promise<void> {
RemoteExtension.ensureLocalBeforeRunCommand(context);
RemoteExtension.ensureLocalBeforeRunCommand("generate device code stub", context);

const rootPath = utils.getFirstWorkspaceFolderPath();
if (!rootPath) {
throw new WorkspaceNotOpenError("generate device code stub");
}

// Check installation of Codegen CLI and update its bits if a new version is
// found
Expand Down Expand Up @@ -131,7 +137,11 @@ export class CodeGeneratorCore {

// Download dependent interface of capability model
if (!(await DigitalTwinUtility.downloadDependentInterface(rootPath, capabilityModelFilePath))) {
throw new OperationFailedError(`Failed to download dependent interface.`);
throw new OperationFailedError(
"download dependent interface",
"",
"Check out error message in the output channel."
);
}

const codeGenExecutionInfo: CodeGenExecutionItem = {
Expand Down Expand Up @@ -314,14 +324,19 @@ export class CodeGeneratorCore {
return connectionType.name === deviceConnectionSelection.label;
});

if (!deviceConnection) {
throw new SystemResourceNotFoundError(
"device connection type",
`${deviceConnectionSelection.label} connection type`,
"CodeGen configuration"
);
}

const connectionType: DeviceConnectionType =
DeviceConnectionType[deviceConnection.type as keyof typeof DeviceConnectionType];

if (!connectionType) {
throw new Error(
`Failed to find an available device connection type with selection label\
'${deviceConnectionSelection.label}' from CodeGen configuration.`
);
throw new TypeNotSupportedError("device connection type", `${deviceConnection.type}`);
}

utils.channelShowAndAppendLine(channel, `Selected device connection type: ${connectionType}`);
Expand All @@ -348,7 +363,7 @@ export class CodeGeneratorCore {
});

if (!projectTemplateItems) {
throw new Error(`Internal error. Unable to find available project templates using ${language} language.`);
throw new SystemResourceNotFoundError("project template", `${language} language`, "CodeGen configuration");
}

const projectTemplateSelection = await vscode.window.showQuickPick(projectTemplateItems, {
Expand All @@ -364,14 +379,19 @@ export class CodeGeneratorCore {
return projectType.name === projectTemplateSelection.label;
});

if (!projectTemplate) {
throw new SystemResourceNotFoundError(
"project template",
`${projectTemplateSelection.label} project template name`,
"CodeGen configuration"
);
}

const codeGenProjectType: CodeGenProjectType =
CodeGenProjectType[projectTemplate.type as keyof typeof CodeGenProjectType];

if (!codeGenProjectType) {
throw new Error(
`Failed to find an available project template with selection label
'${projectTemplateSelection.label}' from CodeGen configuration.`
);
throw new TypeNotSupportedError("CodeGen project type", `${projectTemplate.type}`);
}

utils.channelShowAndAppendLine(channel, `Selected CodeGen project type: ${codeGenProjectType}`);
Expand Down Expand Up @@ -414,21 +434,26 @@ export class CodeGeneratorCore {
return sdkReference.name === deviceConnectionSelection.label;
});

if (!sdkReference) {
throw new SystemResourceNotFoundError(
"SDK reference",
`${deviceConnectionSelection.label} IoT Device SDK reference type`,
"CodeGen configuration"
);
}

const sdkReferenceType: DeviceSdkReferenceType =
DeviceSdkReferenceType[sdkReference.type as keyof typeof DeviceSdkReferenceType];

if (!sdkReference) {
throw new Error(
`Failed to find an available SDK reference type with selection label \
'${deviceConnectionSelection.label}' from CodeGen configuration.`
);
if (!sdkReferenceType) {
throw new TypeNotSupportedError("SDK reference type", `${sdkReference.type}`);
}

deviceSdkReferenceType = sdkReferenceType;
break;
}
default:
throw new Error(`projectType ${projectType} is not supported.`);
throw new TypeNotSupportedError("project type", `${projectType}`);
}

utils.channelShowAndAppendLine(channel, `Selected device SDK reference type: ${deviceSdkReferenceType}`);
Expand Down
4 changes: 2 additions & 2 deletions src/DigitalTwin/DigitalTwinUtility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export class DigitalTwinUtility {
*/
static async selectCapabilityModel(): Promise<string> {
if (!DigitalTwinUtility.extensionInstance) {
throw new DigitalTwinNotInitializedError();
throw new DigitalTwinNotInitializedError("select capability model");
}
let result = "";
try {
Expand All @@ -57,7 +57,7 @@ export class DigitalTwinUtility {
*/
static async downloadDependentInterface(folder: string, capabilityModelFile: string): Promise<boolean> {
if (!DigitalTwinUtility.extensionInstance) {
throw new DigitalTwinNotInitializedError();
throw new DigitalTwinNotInitializedError("download dependent interface");
}
try {
await DigitalTwinUtility.extensionInstance.downloadDependentInterface(folder, capabilityModelFile);
Expand Down
1 change: 0 additions & 1 deletion src/DigitalTwin/pnp/src/common/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ export class Constants {
"Company repository connection string is not found. Please sign out and sign in with a valid connection string";
static readonly PUBLIC_REPOSITORY_URL_NOT_FOUND_MSG = "Public repository url is not found";
static readonly CONNECTION_STRING_INVALID_FORMAT_MSG = "Invalid connection string format";
static readonly MODEL_TYPE_INVALID_MSG = "Invalid model type";
static readonly NEED_OPEN_COMPANY_REPOSITORY_MSG = "Please open company repository and try again";

static readonly NSAT_SURVEY_URL = "https://aka.ms/vscode-iot-workbench-survey";
Expand Down
3 changes: 2 additions & 1 deletion src/DigitalTwin/pnp/src/common/utility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { DeviceModelManager, ModelType } from "../deviceModel/deviceModelManager
import { DigitalTwinConstants } from "../intelliSense/digitalTwinConstants";
import { ModelFileInfo } from "../modelRepository/modelRepositoryManager";
import { Constants } from "./constants";
import { PnPModelTypeInvalidError } from "../../../../common/Error/PnPErrors/PnPModelTypeInvalidError";

/**
* Common utility
Expand Down Expand Up @@ -105,7 +106,7 @@ export class Utility {
): Promise<void> {
const type: ModelType = DeviceModelManager.convertToModelType(content[DigitalTwinConstants.TYPE]);
if (!type) {
throw new Error(Constants.MODEL_TYPE_INVALID_MSG);
throw new PnPModelTypeInvalidError("create model file", type);
}
const replacement = new Map<string, string>();
replacement.set(":", "_");
Expand Down
105 changes: 58 additions & 47 deletions src/Models/AZ3166Device.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import * as WinReg from "winreg";

import { BoardProvider } from "../boardProvider";
import { ArduinoCommands } from "../common/Commands";
import { BoardNotFoundError } from "../common/Error/SystemErrors/BoardNotFoundError";
import { TypeNotSupportedError } from "../common/Error/SystemErrors/TypeNotSupportedError";
import { ResourceNotFoundError } from "../common/Error/OperationFailedErrors/ResourceNotFoundError";
import { OperationCanceledError } from "../common/Error/OperationCanceledError";
Expand All @@ -31,6 +30,9 @@ import { reject } from "bluebird";
import { ArduinoDeviceBase } from "./ArduinoDeviceBase";
import { DeviceType } from "./Interfaces/Device";
import { DeviceConfig, TemplateFileInfo } from "./Interfaces/ProjectTemplate";
import { FileNotFoundError } from "../common/Error/OperationFailedErrors/FileNotFound";
import { DirectoryNotFoundError } from "../common/Error/OperationFailedErrors/DirectoryNotFoundError";
import { SystemResourceNotFoundError } from "../common/Error/SystemErrors/SystemResourceNotFoundError";

const impor = require("impor")(__dirname);
const forEach = impor("lodash.foreach") as typeof import("lodash.foreach");
Expand Down Expand Up @@ -104,9 +106,12 @@ export class AZ3166Device extends ArduinoDeviceBase {

name = "AZ3166";

get board(): Board | undefined {
get board(): Board {
const boardProvider = new BoardProvider(this.boardFolderPath);
const az3166 = boardProvider.find({ id: AZ3166Device._boardId });
if (!az3166) {
throw new SystemResourceNotFoundError("AZ3166 board", `board id ${AZ3166Device._boardId}`, "board list");
}
return az3166;
}

Expand Down Expand Up @@ -211,7 +216,11 @@ export class AZ3166Device extends ArduinoDeviceBase {
// Set credentials
const res = await this.setDeviceConfig(credentials, deviceSettingType); // TODO: Mind the return value.
if (!res) {
throw new OperationFailedError("flush configuration to device");
throw new OperationFailedError(
"flush configuration to device",
"",
"Please check out error message in the output channel."
);
}
let deviceSettingTypeForLog;
switch (deviceSettingType) {
Expand Down Expand Up @@ -276,20 +285,20 @@ export class AZ3166Device extends ArduinoDeviceBase {
*/
private async getDeviceConnectionString(): Promise<string> {
// Get device connection string from workspace config
let deviceConnectionString = ConfigHandler.get<string>(ConfigKey.iotHubDeviceConnectionString);

// Select method to acquire device connection string
const deviceConnectionStringAcquisitionMethodSelection = await this.selectDeviceConnectionStringAcquisitionMethod(
deviceConnectionString
);
const deviceConnectionStringFromConfig = ConfigHandler.get<string>(ConfigKey.iotHubDeviceConnectionString);

if (deviceConnectionStringAcquisitionMethodSelection.label === DeviceConnectionStringAcquisitionMethods.Input) {
deviceConnectionString = await this.getInputDeviceConnectionString();
}
let deviceConnectionString: string;
if (deviceConnectionStringFromConfig) {
// Select method to acquire device connection string
const deviceConnectionStringAcquisitionMethodSelection = await this.selectDeviceConnectionStringAcquisitionMethod(
deviceConnectionStringFromConfig
);

if (!deviceConnectionString) {
throw new OperationFailedError("get device connection string");
if (deviceConnectionStringAcquisitionMethodSelection.label == DeviceConnectionStringAcquisitionMethods.Select) {
deviceConnectionString = deviceConnectionStringFromConfig;
}
}
deviceConnectionString = await this.getInputDeviceConnectionString();

return deviceConnectionString;
}
Expand All @@ -299,7 +308,7 @@ export class AZ3166Device extends ArduinoDeviceBase {
* configuration.
*/
private async selectDeviceConnectionStringAcquisitionMethod(
deviceConnectionString: string | undefined
deviceConnectionString: string
): Promise<vscode.QuickPickItem> {
const deviceConnectionStringAcquisitionOptions = this.getDeviceConnectionStringAcquisitionOptions(
deviceConnectionString
Expand All @@ -316,29 +325,26 @@ export class AZ3166Device extends ArduinoDeviceBase {
return deviceConnectionStringAcquisitionSelection;
}

private getDeviceConnectionStringAcquisitionOptions(
deviceConnectionString: string | undefined
): vscode.QuickPickItem[] {
let hostName = "";
let deviceId = "";
if (deviceConnectionString) {
const hostnameMatches = deviceConnectionString.match(/HostName=(.*?)(;|$)/);
if (hostnameMatches) {
hostName = hostnameMatches[0];
}

const deviceIDMatches = deviceConnectionString.match(/DeviceId=(.*?)(;|$)/);
if (deviceIDMatches) {
deviceId = deviceIDMatches[0];
}
}

private getDeviceConnectionStringAcquisitionOptions(deviceConnectionString: string): vscode.QuickPickItem[] {
let deviceConnectionStringAcquisitionOptions: vscode.QuickPickItem[] = [];
const inputDeviceConnectionStringOption = {
label: DeviceConnectionStringAcquisitionMethods.Input,
description: "",
detail: ""
};

let hostName = "";
let deviceId = "";
const hostnameMatches = deviceConnectionString.match(/HostName=(.*?)(;|$)/);
if (hostnameMatches) {
hostName = hostnameMatches[0];
}

const deviceIDMatches = deviceConnectionString.match(/DeviceId=(.*?)(;|$)/);
if (deviceIDMatches) {
deviceId = deviceIDMatches[0];
}

if (deviceId && hostName) {
deviceConnectionStringAcquisitionOptions = [
{
Expand Down Expand Up @@ -495,7 +501,7 @@ export class AZ3166Device extends ArduinoDeviceBase {
}
}

private async flushDeviceConfigUnixAndMac(configValue: string, option: ConfigDeviceOptions): Promise<boolean> {
private flushDeviceConfigUnixAndMac(configValue: string, option: ConfigDeviceOptions): Promise<boolean> {
return new Promise(
// eslint-disable-next-line no-async-promise-executor
async (resolve: (value: boolean) => void, reject: (value: Error) => void) => {
Expand All @@ -506,7 +512,7 @@ export class AZ3166Device extends ArduinoDeviceBase {
comPort = await this.chooseCOM();
console.log(`Opening ${comPort}.`);
} catch (error) {
reject(error);
return reject(error);
}
if (option === ConfigDeviceOptions.ConnectionString) {
command = "set_az_iothub";
Expand All @@ -517,9 +523,11 @@ export class AZ3166Device extends ArduinoDeviceBase {
}
let errorRejected = false;

const az3166 = this.board;
if (!az3166) {
return reject(new BoardNotFoundError(AZ3166Device._boardId));
let az3166: Board;
try {
az3166 = this.board;
} catch (error) {
return reject(error);
}

const port = new AZ3166Device.serialport(comPort, {
Expand Down Expand Up @@ -594,7 +602,7 @@ export class AZ3166Device extends ArduinoDeviceBase {
);
}

async flushDeviceConfig(configValue: string, option: ConfigDeviceOptions): Promise<boolean> {
private flushDeviceConfig(configValue: string, option: ConfigDeviceOptions): Promise<boolean> {
return new Promise(
// eslint-disable-next-line no-async-promise-executor
async (resolve: (value: boolean) => void, reject: (value: Error) => void) => {
Expand All @@ -619,9 +627,11 @@ export class AZ3166Device extends ArduinoDeviceBase {
let commandExecuted = false;
let gotData = false;

const az3166 = this.board;
if (!az3166) {
return reject(new BoardNotFoundError(AZ3166Device._boardId));
let az3166: Board;
try {
az3166 = this.board;
} catch (error) {
return reject(error);
}

const port = new AZ3166Device.serialport(comPort, {
Expand Down Expand Up @@ -759,10 +769,11 @@ export class AZ3166Device extends ArduinoDeviceBase {
return new Promise(async (resolve: (value: string) => void, reject: (reason: Error) => void) => {
const comList = await this.getComList();

const az3166 = this.board;

if (!az3166) {
return reject(new BoardNotFoundError(AZ3166Device._boardId));
let az3166: Board;
try {
az3166 = this.board;
} catch (error) {
return reject(error);
}

const list = _.filter(comList, com => {
Expand Down Expand Up @@ -882,7 +893,7 @@ export class AZ3166Device extends ArduinoDeviceBase {
}

if (files.length === 0 || files.length > 1) {
throw new ResourceNotFoundError(
throw new FileNotFoundError(
`generate ${constants.platformLocalFileName} file`,
`files under Arduino package installation path ${arduinoPackagePath}`,
"Please clear the path and reinstall the package for Devkit."
Expand All @@ -891,7 +902,7 @@ export class AZ3166Device extends ArduinoDeviceBase {

const directoryName = path.join(arduinoPackagePath, files[0]);
if (!fs.isDirectorySync(directoryName)) {
throw new ResourceNotFoundError(
throw new DirectoryNotFoundError(
`generate ${constants.platformLocalFileName} file`,
"Arduino package for MXChip IoT Devkit",
"Please follow guide to install the DevKit package."
Expand Down
Loading

0 comments on commit edd31c6

Please sign in to comment.