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 {SCM_REVISION, VERSION} from '../../deps_build/trace_processor/ui/tsc/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) { 30 throw new Error(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} ${SCM_REVISION}\n`; 62 errLog += `UA: ${navigator.userAgent}\n`; 63 64 console.error(errLog, err); 65 errorHandler(errLog); 66} 67 68// This function serves two purposes. 69// 1) A runtime check - if we are ever called, we throw an exception. 70// This is useful for checking that code we suspect should never be reached is 71// actually never reached. 72// 2) A compile time check where typescript asserts that the value passed can be 73// cast to the "never" type. 74// This is useful for ensuring we exhastively check union types. 75export function assertUnreachable(_x: never) { 76 throw new Error('This code should not be reachable'); 77} 78