1// Copyright (C) 2018 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import * as version from '../gen/perfetto_version';
16
17export type ErrorHandler = (err: string) => void;
18
19let errorHandler: ErrorHandler = (_: string) => {};
20
21export function assertExists<A>(value: A | null | undefined): A {
22  if (value === null || value === undefined) {
23    throw new Error('Value doesn\'t exist');
24  }
25  return value;
26}
27
28export function assertTrue(value: boolean, optMsg?: string) {
29  if (value !== true) {
30    throw new Error(optMsg ? optMsg : 'Failed assertion');
31  }
32}
33
34export function assertFalse(value: boolean, optMsg?: string) {
35  assertTrue(!value, optMsg);
36}
37
38export function setErrorHandler(handler: ErrorHandler) {
39  errorHandler = handler;
40}
41
42export function reportError(err: ErrorEvent|PromiseRejectionEvent|{}) {
43  let errLog = '';
44  let errorObj = undefined;
45
46  if (err instanceof ErrorEvent) {
47    errLog = err.message;
48    errorObj = err.error;
49  } else if (err instanceof PromiseRejectionEvent) {
50    errLog = `${err.reason}`;
51    errorObj = err.reason;
52  } else {
53    errLog = `${err}`;
54  }
55  if (errorObj !== undefined && errorObj !== null) {
56    const errStack = (errorObj as {stack?: string}).stack;
57    errLog += '\n';
58    errLog += errStack !== undefined ? errStack : JSON.stringify(errorObj);
59  }
60  errLog += '\n\n';
61  errLog += `${version.VERSION} ${version.SCM_REVISION}\n`;
62  errLog += `UA: ${navigator.userAgent}\n`;
63
64  console.error(errLog, err);
65  errorHandler(errLog);
66}
67