Enhance exception handling according to localization, refactor localize calls in src/common folder (#859)

This commit is contained in:
Yuri Skorokhodov 2018-12-13 16:57:40 +03:00 коммит произвёл GitHub
Родитель 4f303d7640
Коммит fc602bb622
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
11 изменённых файлов: 84 добавлений и 78 удалений

Просмотреть файл

@ -117,10 +117,22 @@ function build(failOnError, buildNls) {
});
}
var libtslint = require("tslint");
var tslint = require("gulp-tslint");
gulp.task("tslint", function () {
var program = libtslint.Linter.createProgram("./tsconfig.json");
return gulp.src(lintSources, { base: "." })
.pipe(tslint({
formatter: "verbose",
program: program
}))
.pipe(tslint.report());
});
// TODO: The file property should point to the generated source (this implementation adds an extra folder to the path)
// We should also make sure that we always generate urls in all the path properties (We shouldn"t have \\s. This seems to
// be an issue on Windows platforms)
gulp.task("build", gulp.series("check-imports", "check-copyright", function (done) {
gulp.task("build", gulp.series("check-imports", "check-copyright", "tslint", function (done) {
build(true, true);
done();
}));
@ -130,7 +142,7 @@ gulp.task("build-dev", gulp.series("check-imports", "check-copyright", function
done();
}));
gulp.task("quick-build", build);
gulp.task("quick-build", gulp.series("build-dev"));
gulp.task("watch", gulp.series("build", function () {
log("Watching build sources...");
@ -147,24 +159,13 @@ gulp.task("clean", function () {
"out/",
"!test/resources/sampleReactNative022Project/**/*.js",
".vscode-test/",
"nls.*.json"
"nls.*.json",
"package.nls.*.json"
]
return del(pathsToDelete, { force: true });
});
var libtslint = require("tslint");
var tslint = require("gulp-tslint");
gulp.task("tslint", function () {
var program = libtslint.Linter.createProgram("./tsconfig.json");
return gulp.src(lintSources, { base: "." })
.pipe(tslint({
formatter: "verbose",
program: program
}))
.pipe(tslint.report());
});
gulp.task("default", gulp.series("clean", "build", "tslint"));
gulp.task("default", gulp.series("clean", "build"));
var lintSources = [
srcPath,
@ -273,7 +274,7 @@ gulp.task("release", gulp.series("build", function () {
});
}));
// Creates package.i18n.json files for all languages to {workspaceRoot}/i18n folder
// Creates package.i18n.json files for all languages from {workspaceRoot}/i18n folder into project root
gulp.task("add-i18n", function () {
return gulp.src(["package.nls.json"])
.pipe(nls.createAdditionalLanguageFiles(defaultLanguages, "i18n"))

Просмотреть файл

@ -218,13 +218,11 @@ export class CommandExecutor {
private static getCommandStatusString(command: string, status: CommandStatus) {
switch (status) {
case CommandStatus.Start:
return localize("ExecutingCommand", "Executing command: {0}", command);
return `Executing command: ${command}`;
case CommandStatus.End:
return localize("FinishedExecutingCommand", "Finished executing: {0}", command);
return `Finished executing: ${command}`;
default:
throw new Error(localize("UnsupportedCommandStatus", "Unsupported command status"));
throw ErrorHelper.getInternalError(InternalErrorCode.UnsupportedCommandStatus);
}
}
}

Просмотреть файл

@ -29,7 +29,7 @@ export class ErrorHelper {
}
private static getErrorMessage(errorCode: InternalErrorCode, ...optionalArgs: any[]): string {
return ErrorHelper.formatErrorMessage(ErrorHelper.ERROR_STRINGS[InternalErrorCode[errorCode]], ...optionalArgs);
return ErrorHelper.formatErrorMessage(ErrorHelper.ERROR_STRINGS[errorCode], ...optionalArgs);
}
private static formatErrorMessage(errorMessage: string, ...optionalArgs: any[]): string {

Просмотреть файл

@ -1,43 +1,49 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
import * as nls from "vscode-nls";
import {InternalErrorCode} from "./internalErrorCode";
const localize = nls.loadMessageBundle();
export const ERROR_STRINGS = {
"CommandFailed": localize("CommandFailed", "Error while executing command '{0}'"),
"CommandFailedWithErrorCode": localize("CommandFailedWithErrorCode", "Command '{0}' failed with error code {1}"),
"ExpectedIntegerValue": localize("ExpectedIntegerValue", "Expected an integer. Couldn't read {0}"),
"PackagerStartFailed": localize("PackagerStartFailed", "Error while executing React Native Packager."),
"IOSDeployNotFound": localize("IOSDeployNotFound", "Unable to find ios-deploy. Please make sure to install it globally('npm install -g ios-deploy')"),
"DeviceNotPluggedIn": localize("DeviceNotPluggedIn", "Unable to mount developer disk image."),
"DeveloperDiskImgNotMountable": localize("DeveloperDiskImgNotMountable", "Unable to mount developer disk image."),
"UnableToLaunchApplication": localize("UnableToLaunchApplication", "Unable to launch application."),
"ApplicationLaunchTimedOut": localize("ApplicationLaunchTimedOut", "Timeout launching application. Is the device locked?"),
"IOSSimulatorNotLaunchable": localize("IOSSimulatorNotLaunchable", "Unable to launch iOS simulator. Try specifying a different target."),
"OpnPackagerLocationNotFound": localize("OpnPackagerLocationNotFound", "Opn package location not found"),
"PackageNotFound": localize("PackageNotFound", "Attempting to find package {0} failed with error: {1}"),
"PlatformNotSupported": localize("PlatformNotSupported", "Platform '{0}' is not supported on host platform: {1}"),
"ProjectVersionNotParsable": localize("ProjectVersionNotParsable", "Couldn't parse the version component of the package at {0}: version = {1}"),
"ProjectVersionUnsupported": localize("ProjectVersionUnsupported", "Project version = {0}"),
"ProjectVersionNotReadable": localize("ProjectVersionNotReadable", "Unable to read version = {0}"),
"TelemetryInitializationFailed": localize("TelemetryInitializationFailed", "{0}. Couldn't initialize telemetry"),
"ExtensionActivationFailed": localize("ExtensionActivationFailed", "Failed to activate the React Native Tools extension"),
"DebuggerStubLauncherFailed": localize("DebuggerStubLauncherFailed", "Failed to setup the stub launcher for the debugger"),
"IntellisenseSetupFailed": localize("IntellisenseSetupFailed", "Failed to setup IntelliSense"),
"NodeDebuggerConfigurationFailed": localize("NodeDebuggerConfigurationFailed", "Failed to configure the node debugger location for the debugger"),
"FailedToStopPackagerOnExit": localize("FailedToStopPackagerOnExit", "Failed to stop the packager while closing React Native Tools"),
"FailedToRunOnAndroid": localize("FailedToRunOnAndroid", "Failed to run the application in Android"),
"FailedToRunOnIos": localize("FailedToRunOnIos", "Failed to run the application in iOS"),
"FailedToRunExponent": localize("FailedToRunExponent", "Failed to run the application in Exponent"),
"FailedToPublishToExpHost": localize("FailedToRunExponent", "Failed to publish the application to Exponent"),
"FailedToStartPackager": localize("FailedToStartPackager", "Failed to start the React Native packager"),
"FailedToStopPackager": localize("FailedToStopPackager", "Failed to stop the React Native packager"),
"FailedToRestartPackager": localize("FailedToRestartPackager", "Failed to restart the React Native packager"),
"DebuggingFailed": localize("DebuggingFailed", "Cannot debug application"),
"DebuggingFailedInNodeWrapper": localize("DebuggingFailedInNodeWrapper", "Cannot debug application due to an error in the internal Node Debugger"),
"RNTempFolderDeletionFailed": localize("RNTempFolderDeletionFailed", "Couldn't delete the temporary folder {0}"),
"CouldNotFindLocationOfNodeDebugger": localize("CouldNotFindLocationOfNodeDebugger", "Couldn't find the location of the node-debugger extension"),
"PackagerRunningInDifferentPort": localize("PackagerRunningInDifferentPort", "A packager cannot be started on port {0} because a packager process is already running on port {1}"),
"ErrorWhileProcessingMessageInIPMSServer": localize("ErrorWhileProcessingMessageInIPMSServer", "An error ocurred while handling message: {0}"),
"ErrorNoPipeFound": localize("ErrorNoPipeFound", "Unable to set up communication with VSCode react-native extension. Is this a react-native project, and have you made sure that the react-native npm package is installed at the root?"),
[InternalErrorCode.CommandFailed]: localize("CommandFailed", "Error while executing command '{0}'"),
[InternalErrorCode.CommandFailedWithErrorCode]: localize("CommandFailedWithErrorCode", "Command '{0}' failed with error code {1}"),
[InternalErrorCode.ExpectedIntegerValue]: localize("ExpectedIntegerValue", "Expected an integer. Couldn't read {0}"),
[InternalErrorCode.PackagerStartFailed]: localize("PackagerStartFailed", "Error while executing React Native Packager."),
[InternalErrorCode.IOSDeployNotFound]: localize("IOSDeployNotFound", "Unable to find ios-deploy. Please make sure to install it globally('npm install -g ios-deploy')"),
[InternalErrorCode.DeviceNotPluggedIn]: localize("DeviceNotPluggedIn", "Unable to mount developer disk image."),
[InternalErrorCode.DeveloperDiskImgNotMountable]: localize("DeveloperDiskImgNotMountable", "Unable to mount developer disk image."),
[InternalErrorCode.UnableToLaunchApplication]: localize("UnableToLaunchApplication", "Unable to launch application."),
[InternalErrorCode.ApplicationLaunchTimedOut]: localize("ApplicationLaunchTimedOut", "Timeout launching application. Is the device locked?"),
[InternalErrorCode.IOSSimulatorNotLaunchable]: localize("IOSSimulatorNotLaunchable", "Unable to launch iOS simulator. Try specifying a different target."),
[InternalErrorCode.OpnPackagerLocationNotFound]: localize("OpnPackagerLocationNotFound", "Opn package location not found"),
[InternalErrorCode.OpnPackagerNotFound]: localize("OpnPackagerNotFound", "The package 'opn' was not found. {0}"),
[InternalErrorCode.PackageNotFound]: localize("PackageNotFound", "Attempting to find package {0} failed with error: {1}"),
[InternalErrorCode.PlatformNotSupported]: localize("PlatformNotSupported", "Platform '{0}' is not supported on host platform: {1}"),
[InternalErrorCode.ProjectVersionNotParsable]: localize("ProjectVersionNotParsable", "Couldn't parse the version component of the package at {0}: version = {1}"),
[InternalErrorCode.ProjectVersionUnsupported]: localize("ProjectVersionUnsupported", "Project version = {0}"),
[InternalErrorCode.ProjectVersionNotReadable]: localize("ProjectVersionNotReadable", "Unable to read version = {0}"),
[InternalErrorCode.TelemetryInitializationFailed]: localize("TelemetryInitializationFailed", "{0}. Couldn't initialize telemetry"),
[InternalErrorCode.ExtensionActivationFailed]: localize("ExtensionActivationFailed", "Failed to activate the React Native Tools extension"),
[InternalErrorCode.DebuggerStubLauncherFailed]: localize("DebuggerStubLauncherFailed", "Failed to setup the stub launcher for the debugger"),
[InternalErrorCode.IntellisenseSetupFailed]: localize("IntellisenseSetupFailed", "Failed to setup IntelliSense"),
[InternalErrorCode.NodeDebuggerConfigurationFailed]: localize("NodeDebuggerConfigurationFailed", "Failed to configure the node debugger location for the debugger"),
[InternalErrorCode.FailedToStopPackagerOnExit]: localize("FailedToStopPackagerOnExit", "Failed to stop the packager while closing React Native Tools"),
[InternalErrorCode.FailedToRunOnAndroid]: localize("FailedToRunOnAndroid", "Failed to run the application in Android"),
[InternalErrorCode.FailedToRunOnIos]: localize("FailedToRunOnIos", "Failed to run the application in iOS"),
[InternalErrorCode.FailedToRunExponent]: localize("FailedToRunExponent", "Failed to run the application in Exponent"),
[InternalErrorCode.FailedToPublishToExpHost]: localize("FailedToRunExponent", "Failed to publish the application to Exponent"),
[InternalErrorCode.FailedToStartPackager]: localize("FailedToStartPackager", "Failed to start the React Native packager"),
[InternalErrorCode.FailedToStopPackager]: localize("FailedToStopPackager", "Failed to stop the React Native packager"),
[InternalErrorCode.FailedToRestartPackager]: localize("FailedToRestartPackager", "Failed to restart the React Native packager"),
[InternalErrorCode.DebuggingFailed]: localize("DebuggingFailed", "Cannot debug application"),
[InternalErrorCode.DebuggingFailedInNodeWrapper]: localize("DebuggingFailedInNodeWrapper", "Cannot debug application due to an error in the internal Node Debugger"),
[InternalErrorCode.RNTempFolderDeletionFailed]: localize("RNTempFolderDeletionFailed", "Couldn't delete the temporary folder {0}"),
[InternalErrorCode.CouldNotFindLocationOfNodeDebugger]: localize("CouldNotFindLocationOfNodeDebugger", "Couldn't find the location of the node-debugger extension"),
[InternalErrorCode.PackagerRunningInDifferentPort]: localize("PackagerRunningInDifferentPort", "A packager cannot be started on port {0} because a packager process is already running on port {1}"),
[InternalErrorCode.ErrorWhileProcessingMessageInIPMSServer]: localize("ErrorWhileProcessingMessageInIPMSServer", "An error ocurred while handling message: {0}"),
[InternalErrorCode.ErrorNoPipeFound]: localize("ErrorNoPipeFound", "Unable to set up communication with VSCode react-native extension. Is this a react-native project, and have you made sure that the react-native npm package is installed at the root?"),
[InternalErrorCode.NotAllSuccessPatternsMatched]: localize("NotAllSuccessPatternsMatched", "Unknown error: not all success patterns were matched. \n It means that \"react-native run-{0}\" command failed. \n Please, check the View -> Toggle Output -> React Native, \n View -> Toggle Output -> React Native: Run {1} output windows."),
[InternalErrorCode.CouldNotParsePackageVersion]: localize("CouldNotParsePackageVersion", "Couldn't parse the version component of the package at {0}: version = {1}"),
[InternalErrorCode.UnsupportedCommandStatus]: localize("UnsupportedCommandStatus", "Unsupported command status"),
};

Просмотреть файл

@ -18,7 +18,7 @@ export class InternalError extends Error {
super(message);
this.errorCode = errorCode;
this.errorLevel = errorLevel;
this.message = message;
this.message = message + ` (error code ${this.errorCode})`;
}
}

Просмотреть файл

@ -14,6 +14,7 @@ export enum InternalErrorCode {
FailedToRestartPackager = 109,
FailedToRunExponent = 110,
FailedToPublishToExpHost = 111,
UnsupportedCommandStatus = 112,
// Device Deployer errors
IOSDeployNotFound = 201,
@ -49,6 +50,9 @@ export enum InternalErrorCode {
PlatformNotSupported = 709,
WorkspaceNotFound = 710,
ExpectedExponentTunnelPath = 711,
NotAllSuccessPatternsMatched = 712,
CouldNotParsePackageVersion = 713,
PackageNotFound = 714,
// Activation errors
CouldNotFindLocationOfNodeDebugger = 801,

Просмотреть файл

@ -5,8 +5,8 @@ import * as pathModule from "path";
import * as Q from "q";
import {FileSystem} from "./fileSystem";
import * as nls from "vscode-nls";
const localize = nls.loadMessageBundle();
import { ErrorHelper } from "../error/errorHelper";
import { InternalErrorCode } from "../error/internalErrorCode";
interface IPackageDependencyDict {
[packageName: string]: string;
@ -51,7 +51,7 @@ export class Package {
return this.parseProperty("version").then(version =>
typeof version === "string"
? version
: Q.reject<string>(localize("CouldNotParseVersion", "Couldn't parse the version component of the package at {0}: version = {1}", this.informationJsonFilePath(), version)));
: Q.reject<string>(ErrorHelper.getInternalError(InternalErrorCode.CouldNotParsePackageVersion, this.informationJsonFilePath(), version)));
}
public setMainFile(value: string): Q.Promise<void> {

Просмотреть файл

@ -3,8 +3,8 @@
import * as Q from "q";
import {ISpawnResult} from "./node/childProcess";
import * as nls from "vscode-nls";
const localize = nls.loadMessageBundle();
import { ErrorHelper } from "./error/errorHelper";
import { InternalErrorCode } from "./error/internalErrorCode";
export type PatternToFailure = {
pattern: string | RegExp,
@ -45,9 +45,7 @@ export class OutputVerifier {
}
}).then(successPatterns => {
if (!this.areAllSuccessPatternsPresent(successPatterns)) { // If we don't find all the success patterns, we also fail
const message = localize("ErrorMessageNotAllSuccessPatternsMatched",
"Unknown error: not all success patterns were matched. \n It means that \"react-native run-{0}\" command failed. \n Please, check the View -> Toggle Output -> React Native, \n View -> Toggle Output -> React Native: Run {1} output windows.", this.platformName, this.platformName);
return Q.reject<void>(new Error(message));
return Q.reject<void>(ErrorHelper.getInternalError(InternalErrorCode.NotAllSuccessPatternsMatched, this.platformName, this.platformName));
} // else we found all the success patterns, so we succeed
return Q.resolve(void 0);
});

Просмотреть файл

@ -284,9 +284,9 @@ export class Packager {
fsHelper.exists(fsPath).then(exists =>
exists
? Q.resolve(fsPath)
: Q.reject<string>(localize("OpnPackageLocationNotFound", "opn package location not found")))));
: Q.reject<string>(ErrorHelper.getInternalError(InternalErrorCode.OpnPackagerLocationNotFound)))));
} catch (err) {
return Q.reject<string>(localize("ThePackageOpnWasNotFound", "The package 'opn' was not found. ") + err);
return Q.reject<string>(ErrorHelper.getInternalError(InternalErrorCode.OpnPackagerNotFound, err));
}
}
@ -324,10 +324,10 @@ export class Packager {
return helper.isExpoApp(false)
.then((isExpo) => {
if (isExpo) {
this.logger.debug(localize("StoppingExponent", "Stopping Exponent"));
this.logger.debug("Stopping Exponent");
return XDL.stopAll(this.projectPath)
.then(() => {
this.logger.debug(localize("ExponentStopped", "Exponent Stopped"));
this.logger.debug("Exponent Stopped");
})
.catch((err) => {
if (err.code === "NOT_LOGGED_IN") {

Просмотреть файл

@ -5,8 +5,6 @@ import * as os from "os";
import {ErrorHelper} from "./error/errorHelper";
import {HostPlatform} from "./hostPlatform";
import {InternalErrorCode} from "./error/internalErrorCode";
import * as nls from "vscode-nls";
const localize = nls.loadMessageBundle();
/**
* Defines the identifiers of all the mobile target platforms React Native supports.
*/
@ -33,7 +31,7 @@ export class TargetPlatformHelper {
case "wpf":
return TargetPlatformId.WINDOWS;
default:
throw new Error( localize("TargetPlatformIsNotSupported", "The target platform {0} is not supported.", platformName));
throw ErrorHelper.getInternalError(InternalErrorCode.PlatformNotSupported, platformName, os.platform());
}
}

Просмотреть файл

@ -17,6 +17,7 @@ import {SettingsHelper} from "../settingsHelper";
import {RemoteExtension} from "../../common/remoteExtension";
import {ReactNativeProjectHelper} from "../../common/reactNativeProjectHelper";
import {TelemetryHelper} from "../../common/telemetryHelper";
import { InternalErrorCode } from "../../common/error/internalErrorCode";
export class IOSPlatform extends GeneralMobilePlatform {
public static DEFAULT_IOS_PROJECT_RELATIVE_PATH = "ios";
@ -33,13 +34,13 @@ export class IOSPlatform extends GeneralMobilePlatform {
// We should add the common iOS build/run errors we find to this list
private static RUN_IOS_FAILURE_PATTERNS: PatternToFailure[] = [{
pattern: "No devices are booted",
message: ErrorHelper.ERROR_STRINGS.IOSSimulatorNotLaunchable,
message: ErrorHelper.ERROR_STRINGS[InternalErrorCode.IOSSimulatorNotLaunchable],
}, {
pattern: "FBSOpenApplicationErrorDomain",
message: ErrorHelper.ERROR_STRINGS.IOSSimulatorNotLaunchable,
message: ErrorHelper.ERROR_STRINGS[InternalErrorCode.IOSSimulatorNotLaunchable],
}, {
pattern: "ios-deploy",
message: ErrorHelper.ERROR_STRINGS.IOSDeployNotFound,
message: ErrorHelper.ERROR_STRINGS[InternalErrorCode.IOSDeployNotFound],
}];
private static RUN_IOS_SUCCESS_PATTERNS = ["BUILD SUCCEEDED"];