microsoft/vscode-react-native
Publicmirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable
src/common/error/errorHelper.ts
64lines · 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 { InternalError, NestedError, InternalErrorLevel } from "./internalError"; |
| 5 | import { InternalErrorCode } from "./internalErrorCode"; |
| 6 | import { ERROR_STRINGS } from "./errorStrings"; |
| 7 | |
| 8 | export class ErrorHelper { |
| 9 | public static ERROR_STRINGS = ERROR_STRINGS; |
| 10 | public static getInternalError( |
| 11 | errorCode: InternalErrorCode, |
| 12 | ...optionalArgs: any[] |
| 13 | ): InternalError { |
| 14 | let message = ErrorHelper.getErrorMessage(errorCode, ...optionalArgs); |
| 15 | return new InternalError(<number>errorCode, message); |
| 16 | } |
| 17 | |
| 18 | public static getNestedError( |
| 19 | innerError: Error, |
| 20 | errorCode: InternalErrorCode, |
| 21 | ...optionalArgs: any[] |
| 22 | ): NestedError { |
| 23 | let message = ErrorHelper.getErrorMessage(errorCode, ...optionalArgs); |
| 24 | return new NestedError(<number>errorCode, message, innerError); |
| 25 | } |
| 26 | |
| 27 | public static wrapError(error: InternalError, innerError: Error): NestedError { |
| 28 | return NestedError.getWrappedError(error, innerError); |
| 29 | } |
| 30 | |
| 31 | public static getWarning(message: string): InternalError { |
| 32 | return new InternalError(-1, message, InternalErrorLevel.Warning); |
| 33 | } |
| 34 | |
| 35 | public static getNestedWarning(innerError: Error, message: string): NestedError { |
| 36 | return new NestedError( |
| 37 | -1, |
| 38 | message, |
| 39 | innerError, |
| 40 | null /* extras */, |
| 41 | InternalErrorLevel.Warning, |
| 42 | ); |
| 43 | } |
| 44 | |
| 45 | private static getErrorMessage(errorCode: InternalErrorCode, ...optionalArgs: any[]): string { |
| 46 | return ErrorHelper.formatErrorMessage( |
| 47 | ErrorHelper.ERROR_STRINGS[errorCode], |
| 48 | ...optionalArgs, |
| 49 | ); |
| 50 | } |
| 51 | |
| 52 | private static formatErrorMessage(errorMessage: string, ...optionalArgs: any[]): string { |
| 53 | if (!errorMessage) { |
| 54 | return errorMessage; |
| 55 | } |
| 56 | |
| 57 | let result: string = <string>errorMessage; |
| 58 | for (let i: number = 0; i < optionalArgs.length; i++) { |
| 59 | result = result.replace(new RegExp("\\{" + i + "\\}", "g"), optionalArgs[i]); |
| 60 | } |
| 61 | |
| 62 | return result; |
| 63 | } |
| 64 | } |
| 65 | |