Commit a89d629b by Andrej Ocenas Committed by GitHub

Tracing: Add some error handling to JaegerQueryField (#23599)

parent 40114e8c
...@@ -6,7 +6,8 @@ export interface AppEvent<T> { ...@@ -6,7 +6,8 @@ export interface AppEvent<T> {
} }
export type AlertPayload = [string, string?]; export type AlertPayload = [string, string?];
export type AlertErrorPayload = [string, (string | Error)?];
export const alertSuccess = eventFactory<AlertPayload>('alert-success'); export const alertSuccess = eventFactory<AlertPayload>('alert-success');
export const alertWarning = eventFactory<AlertPayload>('alert-warning'); export const alertWarning = eventFactory<AlertPayload>('alert-warning');
export const alertError = eventFactory<AlertPayload>('alert-error'); export const alertError = eventFactory<AlertErrorPayload>('alert-error');
...@@ -32,7 +32,11 @@ export const createSuccessNotification = (title: string, text = ''): AppNotifica ...@@ -32,7 +32,11 @@ export const createSuccessNotification = (title: string, text = ''): AppNotifica
id: Date.now(), id: Date.now(),
}); });
export const createErrorNotification = (title: string, text = '', component?: React.ReactElement): AppNotification => { export const createErrorNotification = (
title: string,
text: string | Error = '',
component?: React.ReactElement
): AppNotification => {
return { return {
...defaultErrorNotification, ...defaultErrorNotification,
text: getMessageFromError(text), text: getMessageFromError(text),
......
...@@ -15,7 +15,7 @@ describe('errors functions', () => { ...@@ -15,7 +15,7 @@ describe('errors functions', () => {
describe('when getMessageFromError gets an error object with message field', () => { describe('when getMessageFromError gets an error object with message field', () => {
beforeEach(() => { beforeEach(() => {
message = getMessageFromError({ message: 'error string' }); message = getMessageFromError({ message: 'error string' } as Error);
}); });
it('should return the message text', () => { it('should return the message text', () => {
...@@ -25,7 +25,7 @@ describe('errors functions', () => { ...@@ -25,7 +25,7 @@ describe('errors functions', () => {
describe('when getMessageFromError gets an error object with data.message field', () => { describe('when getMessageFromError gets an error object with data.message field', () => {
beforeEach(() => { beforeEach(() => {
message = getMessageFromError({ data: { message: 'error string' } }); message = getMessageFromError({ data: { message: 'error string' } } as any);
}); });
it('should return the message text', () => { it('should return the message text', () => {
...@@ -35,7 +35,7 @@ describe('errors functions', () => { ...@@ -35,7 +35,7 @@ describe('errors functions', () => {
describe('when getMessageFromError gets an error object with statusText field', () => { describe('when getMessageFromError gets an error object with statusText field', () => {
beforeEach(() => { beforeEach(() => {
message = getMessageFromError({ statusText: 'error string' }); message = getMessageFromError({ statusText: 'error string' } as any);
}); });
it('should return the statusText text', () => { it('should return the statusText text', () => {
...@@ -45,7 +45,7 @@ describe('errors functions', () => { ...@@ -45,7 +45,7 @@ describe('errors functions', () => {
describe('when getMessageFromError gets an error object', () => { describe('when getMessageFromError gets an error object', () => {
beforeEach(() => { beforeEach(() => {
message = getMessageFromError({ customError: 'error string' }); message = getMessageFromError({ customError: 'error string' } as any);
}); });
it('should return the stringified error', () => { it('should return the stringified error', () => {
......
import _ from 'lodash'; import _ from 'lodash';
export function getMessageFromError(err: any): string | null { export function getMessageFromError(err: string | (Error & { data?: any; statusText?: string })): string | null {
if (err && !_.isString(err)) { if (err && !_.isString(err)) {
if (err.message) { if (err.message) {
return err.message; return err.message;
...@@ -13,5 +13,5 @@ export function getMessageFromError(err: any): string | null { ...@@ -13,5 +13,5 @@ export function getMessageFromError(err: any): string | null {
} }
} }
return err; return err as string;
} }
import React from 'react';
import { JaegerQueryField } from './QueryField';
import { shallow } from 'enzyme';
import { JaegerDatasource, JaegerQuery } from './datasource';
import { ButtonCascader } from '@grafana/ui';
describe('JaegerQueryField', function() {
it('shows empty value if no services returned', function() {
const dsMock: JaegerDatasource = {
metadataRequest(url: string) {
if (url.indexOf('/services') > 0) {
return Promise.resolve([]);
}
throw new Error(`Unexpected url: ${url}`);
},
} as any;
const wrapper = shallow(
<JaegerQueryField
history={[]}
datasource={dsMock}
query={{ query: '1234' } as JaegerQuery}
onRunQuery={() => {}}
onChange={() => {}}
/>
);
expect(wrapper.find(ButtonCascader).props().options[0].label).toBe('No traces found');
});
});
...@@ -2,7 +2,8 @@ import React from 'react'; ...@@ -2,7 +2,8 @@ import React from 'react';
import { JaegerDatasource, JaegerQuery } from './datasource'; import { JaegerDatasource, JaegerQuery } from './datasource';
import { ButtonCascader, CascaderOption } from '@grafana/ui'; import { ButtonCascader, CascaderOption } from '@grafana/ui';
import { ExploreQueryFieldProps } from '@grafana/data'; import { AppEvents, ExploreQueryFieldProps } from '@grafana/data';
import { appEvents } from '../../../core/core';
const ALL_OPERATIONS_KEY = '__ALL__'; const ALL_OPERATIONS_KEY = '__ALL__';
const NO_TRACES_KEY = '__NO_TRACES__'; const NO_TRACES_KEY = '__NO_TRACES__';
...@@ -21,6 +22,8 @@ function getLabelFromTrace(trace: any): string { ...@@ -21,6 +22,8 @@ function getLabelFromTrace(trace: any): string {
} }
export class JaegerQueryField extends React.PureComponent<Props, State> { export class JaegerQueryField extends React.PureComponent<Props, State> {
private _isMounted: boolean;
constructor(props: Props, context: React.Context<any>) { constructor(props: Props, context: React.Context<any>) {
super(props, context); super(props, context);
this.state = { this.state = {
...@@ -29,16 +32,24 @@ export class JaegerQueryField extends React.PureComponent<Props, State> { ...@@ -29,16 +32,24 @@ export class JaegerQueryField extends React.PureComponent<Props, State> {
} }
componentDidMount() { componentDidMount() {
this._isMounted = true;
this.getServices(); this.getServices();
} }
componentWillUnmount(): void {
this._isMounted = false;
}
async getServices() { async getServices() {
const url = '/api/services'; const url = '/api/services';
const { datasource } = this.props; const { datasource } = this.props;
try { try {
const res = await datasource.metadataRequest(url); const services: string[] | null = await datasource.metadataRequest(url);
if (res) { if (!this._isMounted) {
const services = res as string[]; return;
}
if (services) {
const serviceOptions: CascaderOption[] = services.sort().map(service => ({ const serviceOptions: CascaderOption[] = services.sort().map(service => ({
label: service, label: service,
value: service, value: service,
...@@ -47,7 +58,7 @@ export class JaegerQueryField extends React.PureComponent<Props, State> { ...@@ -47,7 +58,7 @@ export class JaegerQueryField extends React.PureComponent<Props, State> {
this.setState({ serviceOptions }); this.setState({ serviceOptions });
} }
} catch (error) { } catch (error) {
console.error(error); appEvents.emit(AppEvents.alertError, ['Failed to load services from Jaeger', error]);
} }
} }
...@@ -56,6 +67,10 @@ export class JaegerQueryField extends React.PureComponent<Props, State> { ...@@ -56,6 +67,10 @@ export class JaegerQueryField extends React.PureComponent<Props, State> {
if (selectedOptions.length === 1) { if (selectedOptions.length === 1) {
// Load operations // Load operations
const operations: string[] = await this.findOperations(service); const operations: string[] = await this.findOperations(service);
if (!this._isMounted) {
return;
}
const allOperationsOption: CascaderOption = { const allOperationsOption: CascaderOption = {
label: '[ALL]', label: '[ALL]',
value: ALL_OPERATIONS_KEY, value: ALL_OPERATIONS_KEY,
...@@ -85,6 +100,10 @@ export class JaegerQueryField extends React.PureComponent<Props, State> { ...@@ -85,6 +100,10 @@ export class JaegerQueryField extends React.PureComponent<Props, State> {
const operationValue = selectedOptions[1].value; const operationValue = selectedOptions[1].value;
const operation = operationValue === ALL_OPERATIONS_KEY ? '' : operationValue; const operation = operationValue === ALL_OPERATIONS_KEY ? '' : operationValue;
const traces: any[] = await this.findTraces(service, operation); const traces: any[] = await this.findTraces(service, operation);
if (!this._isMounted) {
return;
}
let traceOptions: CascaderOption[] = traces.map(trace => ({ let traceOptions: CascaderOption[] = traces.map(trace => ({
label: getLabelFromTrace(trace), label: getLabelFromTrace(trace),
value: trace.traceID, value: trace.traceID,
...@@ -128,7 +147,7 @@ export class JaegerQueryField extends React.PureComponent<Props, State> { ...@@ -128,7 +147,7 @@ export class JaegerQueryField extends React.PureComponent<Props, State> {
try { try {
return await datasource.metadataRequest(url); return await datasource.metadataRequest(url);
} catch (error) { } catch (error) {
console.error(error); appEvents.emit(AppEvents.alertError, ['Failed to load operations from Jaeger', error]);
} }
return []; return [];
}; };
...@@ -151,7 +170,7 @@ export class JaegerQueryField extends React.PureComponent<Props, State> { ...@@ -151,7 +170,7 @@ export class JaegerQueryField extends React.PureComponent<Props, State> {
try { try {
return await datasource.metadataRequest(url, traceSearch); return await datasource.metadataRequest(url, traceSearch);
} catch (error) { } catch (error) {
console.error(error); appEvents.emit(AppEvents.alertError, ['Failed to load traces from Jaeger', error]);
} }
return []; return [];
}; };
...@@ -168,12 +187,13 @@ export class JaegerQueryField extends React.PureComponent<Props, State> { ...@@ -168,12 +187,13 @@ export class JaegerQueryField extends React.PureComponent<Props, State> {
render() { render() {
const { query, onChange } = this.props; const { query, onChange } = this.props;
const { serviceOptions } = this.state; const { serviceOptions } = this.state;
const cascaderOptions = serviceOptions && serviceOptions.length ? serviceOptions : noTracesFoundOptions;
return ( return (
<> <>
<div className="gf-form-inline gf-form-inline--nowrap"> <div className="gf-form-inline gf-form-inline--nowrap">
<div className="gf-form flex-shrink-0"> <div className="gf-form flex-shrink-0">
<ButtonCascader options={serviceOptions} onChange={this.onSelectTrace} loadData={this.onLoadOptions}> <ButtonCascader options={cascaderOptions} onChange={this.onSelectTrace} loadData={this.onLoadOptions}>
Traces Traces
</ButtonCascader> </ButtonCascader>
</div> </div>
...@@ -199,4 +219,15 @@ export class JaegerQueryField extends React.PureComponent<Props, State> { ...@@ -199,4 +219,15 @@ export class JaegerQueryField extends React.PureComponent<Props, State> {
} }
} }
const noTracesFoundOptions = [
{
label: 'No traces found',
value: 'no_traces',
isLeaf: true,
// Cannot be disabled because then cascader shows 'loading' for some reason.
// disabled: true,
},
];
export default JaegerQueryField; export default JaegerQueryField;
...@@ -26,7 +26,7 @@ export class JaegerDatasource extends DataSourceApi<JaegerQuery> { ...@@ -26,7 +26,7 @@ export class JaegerDatasource extends DataSourceApi<JaegerQuery> {
super(instanceSettings); super(instanceSettings);
} }
async metadataRequest(url: string, params?: Record<string, any>) { async metadataRequest(url: string, params?: Record<string, any>): Promise<any> {
const res = await this._request(url, params, { silent: true }).toPromise(); const res = await this._request(url, params, { silent: true }).toPromise();
return res.data.data; return res.data.data;
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment