microsoft/vscode-react-native
Publicmirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable
src/common/error/errorHelper.ts
52lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT license. See LICENSE file in the project root for details. |
| 3 | |
| 4 | import * as util from "util"; |
| 5 | import * as path from "path"; |
| 6 | import {InternalError, NestedError, InternalErrorLevel} from "./internalError"; |
| 7 | import {InternalErrorCode} from "./internalErrorCode"; |
| 8 | |
| 9 | export class ErrorHelper { |
| 10 | private static errorStringsJsonLoc = path.resolve(__dirname, "..", "..", "..", "errorStrings", "errorStrings.json"); |
| 11 | public static getInternalError(errorCode: InternalErrorCode, ...optionalArgs: any[]): InternalError { |
| 12 | let message = util.format(ErrorHelper.getErrorMessage(errorCode), optionalArgs); |
| 13 | return new InternalError(<number> errorCode, message); |
| 14 | } |
| 15 | |
| 16 | public static getNestedError(innerError: Error, errorCode: InternalErrorCode, ...optionalArgs: any[]): NestedError { |
| 17 | let message = util.format(ErrorHelper.getErrorMessage(errorCode), optionalArgs); |
| 18 | return new NestedError(<number> errorCode, message, innerError); |
| 19 | } |
| 20 | |
| 21 | public static wrapError(error: InternalError, innerError: Error): NestedError { |
| 22 | return NestedError.getWrappedError(error, innerError); |
| 23 | } |
| 24 | public static getWarning(warningMessage: string, ...optionalArgs: any[]): InternalError { |
| 25 | let message = util.format(warningMessage, optionalArgs); |
| 26 | |
| 27 | // Warnings do not use error codes |
| 28 | return new InternalError(-1, message, InternalErrorLevel.Warning); |
| 29 | } |
| 30 | |
| 31 | private static getErrorMessage(errorCode: InternalErrorCode, ...optionalArgs: any[]): string { |
| 32 | console.log(ErrorHelper.errorStringsJsonLoc); |
| 33 | let errorStrings = require (ErrorHelper.errorStringsJsonLoc); |
| 34 | return ErrorHelper.formatErrorMessage(errorStrings[InternalErrorCode[errorCode]], optionalArgs); |
| 35 | } |
| 36 | |
| 37 | private static formatErrorMessage(errorMessage: string, ...optionalArgs: any[]): string { |
| 38 | if (!errorMessage) { |
| 39 | return errorMessage; |
| 40 | } |
| 41 | |
| 42 | let result: string = <string> errorMessage; |
| 43 | let args: string[] = Array.prototype.slice.call(arguments, 1); |
| 44 | if (args) { |
| 45 | for (var i: number = 0; i < args.length; i++) { |
| 46 | result = result.replace(new RegExp("\\{" + i + "\\}", "g"), args[i]); |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | return result; |
| 51 | } |
| 52 | } |
| 53 | |