errors.ts 6.9 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

import platform = require('vs/base/common/platform');
import types = require('vs/base/common/types');
J
Johannes Rieken 已提交
9
import { IAction } from 'vs/base/common/actions';
E
Erich Gamma 已提交
10
import Severity from 'vs/base/common/severity';
A
Alex Dima 已提交
11 12 13 14 15 16 17 18 19 20
import { TPromise, IPromiseError, IPromiseErrorDetail } from 'vs/base/common/winjs.base';

// ------ BEGIN Hook up error listeners to winjs promises

let outstandingPromiseErrors: { [id: string]: IPromiseErrorDetail; } = {};
function promiseErrorHandler(e: IPromiseError): void {

	//
	// e.detail looks like: { exception, error, promise, handler, id, parent }
	//
21 22
	const details = e.detail;
	const id = details.id;
A
Alex Dima 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41

	// If the error has a parent promise then this is not the origination of the
	//  error so we check if it has a handler, and if so we mark that the error
	//  was handled by removing it from outstandingPromiseErrors
	//
	if (details.parent) {
		if (details.handler && outstandingPromiseErrors) {
			delete outstandingPromiseErrors[id];
		}
		return;
	}

	// Indicate that this error was originated and needs to be handled
	outstandingPromiseErrors[id] = details;

	// The first time the queue fills up this iteration, schedule a timeout to
	// check if any errors are still unhandled.
	if (Object.keys(outstandingPromiseErrors).length === 1) {
		setTimeout(function () {
42
			const errors = outstandingPromiseErrors;
A
Alex Dima 已提交
43 44
			outstandingPromiseErrors = {};
			Object.keys(errors).forEach(function (errorId) {
45
				const error = errors[errorId];
A
Alex Dima 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
				if (error.exception) {
					onUnexpectedError(error.exception);
				} else if (error.error) {
					onUnexpectedError(error.error);
				}
				console.log('WARNING: Promise with no error callback:' + error.id);
				console.log(error);
				if (error.exception) {
					console.log(error.exception.stack);
				}
			});
		}, 0);
	}
}
TPromise.addEventListener('error', promiseErrorHandler);

// ------ END Hook up error listeners to winjs promises
E
Erich Gamma 已提交
63 64 65 66 67 68 69 70 71

export interface ErrorListenerCallback {
	(error: any): void;
}

export interface ErrorListenerUnbind {
	(): void;
}

72
// Avoid circular dependency on EventEmitter by implementing a subset of the interface.
E
Erich Gamma 已提交
73 74 75 76 77 78 79 80
export class ErrorHandler {
	private unexpectedErrorHandler: (e: any) => void;
	private listeners: ErrorListenerCallback[];

	constructor() {

		this.listeners = [];

J
Johannes Rieken 已提交
81
		this.unexpectedErrorHandler = function (e: any) {
E
Erich Gamma 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
			platform.setTimeout(() => {
				if (e.stack) {
					throw new Error(e.message + '\n\n' + e.stack);
				}

				throw e;
			}, 0);
		};
	}

	public addListener(listener: ErrorListenerCallback): ErrorListenerUnbind {
		this.listeners.push(listener);

		return () => {
			this._removeListener(listener);
		};
	}

	private emit(e: any): void {
		this.listeners.forEach((listener) => {
			listener(e);
		});
	}

	private _removeListener(listener: ErrorListenerCallback): void {
		this.listeners.splice(this.listeners.indexOf(listener), 1);
	}

	public setUnexpectedErrorHandler(newUnexpectedErrorHandler: (e: any) => void): void {
		this.unexpectedErrorHandler = newUnexpectedErrorHandler;
	}

	public getUnexpectedErrorHandler(): (e: any) => void {
		return this.unexpectedErrorHandler;
	}

	public onUnexpectedError(e: any): void {
		this.unexpectedErrorHandler(e);
		this.emit(e);
	}
122 123 124 125 126

	// For external errors, we don't want the listeners to be called
	public onUnexpectedExternalError(e: any): void {
		this.unexpectedErrorHandler(e);
	}
E
Erich Gamma 已提交
127 128
}

129
export const errorHandler = new ErrorHandler();
E
Erich Gamma 已提交
130 131 132 133 134

export function setUnexpectedErrorHandler(newUnexpectedErrorHandler: (e: any) => void): void {
	errorHandler.setUnexpectedErrorHandler(newUnexpectedErrorHandler);
}

R
Ron Buckton 已提交
135
export function onUnexpectedError(e: any): undefined {
E
Erich Gamma 已提交
136 137 138 139
	// ignore errors from cancelled promises
	if (!isPromiseCanceledError(e)) {
		errorHandler.onUnexpectedError(e);
	}
R
Ron Buckton 已提交
140
	return undefined;
E
Erich Gamma 已提交
141 142
}

R
Ron Buckton 已提交
143
export function onUnexpectedExternalError(e: any): undefined {
144 145 146 147
	// ignore errors from cancelled promises
	if (!isPromiseCanceledError(e)) {
		errorHandler.onUnexpectedExternalError(e);
	}
R
Ron Buckton 已提交
148
	return undefined;
149 150
}

R
Ron Buckton 已提交
151 152
export function onUnexpectedPromiseError<T>(promise: TPromise<T>): TPromise<T | void> {
	return promise.then(null, onUnexpectedError);
153 154
}

E
Erich Gamma 已提交
155
export function transformErrorForSerialization(error: any): any {
156
	if (error instanceof Error) {
A
Alex Dima 已提交
157
		let { name, message } = error;
A
Alex Dima 已提交
158
		let stack: string = (<any>error).stacktrace || (<any>error).stack;
159 160 161 162 163 164
		return {
			$isError: true,
			name,
			message,
			stack
		};
E
Erich Gamma 已提交
165
	}
166 167 168

	// return as is
	return error;
E
Erich Gamma 已提交
169 170
}

171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
// see https://github.com/v8/v8/wiki/Stack%20Trace%20API#basic-stack-traces
export interface V8CallSite {
	getThis(): any;
	getTypeName(): string;
	getFunction(): string;
	getFunctionName(): string;
	getMethodName(): string;
	getFileName(): string;
	getLineNumber(): number;
	getColumnNumber(): number;
	getEvalOrigin(): string;
	isToplevel(): boolean;
	isEval(): boolean;
	isNative(): boolean;
	isConstructor(): boolean;
	toString(): string;
}

189
const canceledName = 'Canceled';
E
Erich Gamma 已提交
190 191 192 193 194 195 196 197 198

/**
 * Checks if the given error is a promise in canceled state
 */
export function isPromiseCanceledError(error: any): boolean {
	return error instanceof Error && error.name === canceledName && error.message === canceledName;
}

/**
P
Pascal Borreli 已提交
199
 * Returns an error that signals cancellation.
E
Erich Gamma 已提交
200 201
 */
export function canceled(): Error {
B
Benjamin Pasero 已提交
202
	let error = new Error(canceledName);
E
Erich Gamma 已提交
203 204 205 206 207 208 209 210
	error.name = error.message;
	return error;
}

/**
 * Returns an error that signals something is not implemented.
 */
export function notImplemented(): Error {
211
	return new Error('Not Implemented');
E
Erich Gamma 已提交
212 213 214 215
}

export function illegalArgument(name?: string): Error {
	if (name) {
216
		return new Error(`Illegal argument: ${name}`);
E
Erich Gamma 已提交
217
	} else {
218
		return new Error('Illegal argument');
E
Erich Gamma 已提交
219 220 221 222 223
	}
}

export function illegalState(name?: string): Error {
	if (name) {
224
		return new Error(`Illegal state: ${name}`);
E
Erich Gamma 已提交
225
	} else {
226
		return new Error('Illegal state');
E
Erich Gamma 已提交
227 228 229
	}
}

J
Johannes Rieken 已提交
230 231 232 233
export function readonly(name?: string): Error {
	return name
		? new Error(`readonly property '${name} cannot be changed'`)
		: new Error('readonly property cannot be changed');
E
Erich Gamma 已提交
234 235
}

236 237 238 239 240 241
export function disposed(what: string): Error {
	const result = new Error(`${what} has been disposed`);
	result.name = 'DISPOSED';
	return result;
}

E
Erich Gamma 已提交
242 243 244 245 246 247
export interface IErrorOptions {
	severity?: Severity;
	actions?: IAction[];
}

export function create(message: string, options: IErrorOptions = {}): Error {
B
Benjamin Pasero 已提交
248
	let result = new Error(message);
E
Erich Gamma 已提交
249 250 251 252 253 254 255 256 257 258

	if (types.isNumber(options.severity)) {
		(<any>result).severity = options.severity;
	}

	if (options.actions) {
		(<any>result).actions = options.actions;
	}

	return result;
J
Joao Moreno 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
}

export function getErrorMessage(err: any): string {
	if (!err) {
		return 'Error';
	}

	if (err.message) {
		return err.message;
	}

	if (err.stack) {
		return err.stack.split('\n')[0];
	}

	return String(err);
275
}