File size: 1,433 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
import wpcom from 'calypso/lib/wp';
import { getLogger } from 'calypso/server/lib/logger';
import { isDevelopmentMode } from './misc';
// SSR safety: Fail TypeScript compilation if `window` is used without an explicit undefined check
declare const window: undefined | ( Window & typeof globalThis );
/**
* Log an error to the server.
* Works in SSR.
*
* Should never throw.
* @param error Error to save
*/
export const logError = ( error: Record< string, string > & { message: string } ): void => {
const onError = ( e: unknown ) => {
if ( isDevelopmentMode ) {
// eslint-disable-next-line no-console
console.error( '[ExPlat] Unable to send error to server:', e );
}
};
try {
const { message, ...properties } = error;
const logStashError = {
message,
properties: {
...properties,
context: 'explat',
explat_client: 'calypso',
message,
},
};
if ( typeof window === 'undefined' ) {
// Bunyan logger will log to the console in development mode.
getLogger().error( logStashError );
} else if ( isDevelopmentMode ) {
// eslint-disable-next-line no-console
console.error( '[ExPlat] ', error.message, error );
} else {
wpcom.req.post(
{
path: '/js-error',
apiNamespace: 'rest/v1.1',
body: {
error: JSON.stringify( logStashError ),
},
},
( err: unknown ) => err && onError( err )
);
}
} catch ( e ) {
onError( e );
}
};
|