packages/core: add observable consumer to ErrorApi
This commit is contained in:
@@ -15,6 +15,7 @@
|
||||
*/
|
||||
|
||||
import { createApiRef } from '../ApiRef';
|
||||
import { Observable } from '../../types';
|
||||
|
||||
/**
|
||||
* Mirrors the javascript Error class, for the purpose of
|
||||
@@ -54,6 +55,11 @@ export type ErrorApi = {
|
||||
* Post an error for handling by the application.
|
||||
*/
|
||||
post(error: Error, context?: ErrorContext): void;
|
||||
|
||||
/**
|
||||
* Observe errors posted by other parts of the application.
|
||||
*/
|
||||
error$(): Observable<{ error: Error; context?: ErrorContext }>;
|
||||
};
|
||||
|
||||
export const errorApiRef = createApiRef<ErrorApi>({
|
||||
|
||||
@@ -14,32 +14,26 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
import { ErrorApi, ErrorContext, AlertApi } from '../../../';
|
||||
|
||||
type SubscriberFunc = (error: Error) => void;
|
||||
type Unsubscribe = () => void;
|
||||
import { PublishSubject } from './lib';
|
||||
import { Observable } from '../../types';
|
||||
|
||||
export class ErrorApiForwarder implements ErrorApi {
|
||||
private readonly subscribers = new Set<SubscriberFunc>();
|
||||
private alertApi: AlertApi;
|
||||
private readonly subject = new PublishSubject<{
|
||||
error: Error;
|
||||
context?: ErrorContext;
|
||||
}>();
|
||||
|
||||
constructor(alertApi: AlertApi) {
|
||||
this.alertApi = alertApi;
|
||||
}
|
||||
constructor(private readonly alertApi: AlertApi) {}
|
||||
|
||||
post(error: Error, context?: ErrorContext) {
|
||||
if (context?.hidden) {
|
||||
return;
|
||||
if (!context?.hidden) {
|
||||
this.alertApi.post({ message: error.message, severity: 'error' });
|
||||
}
|
||||
|
||||
this.alertApi.post({ message: error.message, severity: 'error' });
|
||||
this.subscribers.forEach(subscriber => subscriber(error));
|
||||
this.subject.next({ error, context });
|
||||
}
|
||||
|
||||
subscribe(func: SubscriberFunc): Unsubscribe {
|
||||
this.subscribers.add(func);
|
||||
|
||||
return () => {
|
||||
this.subscribers.delete(func);
|
||||
};
|
||||
error$(): Observable<{ error: Error; context?: ErrorContext }> {
|
||||
return this.subject;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,6 +44,7 @@ const apiRegistry = ApiRegistry.from([
|
||||
post(error) {
|
||||
throw error;
|
||||
},
|
||||
error$: jest.fn(),
|
||||
} as ErrorApi,
|
||||
],
|
||||
]);
|
||||
|
||||
@@ -53,7 +53,7 @@ describe('CreateAudit', () => {
|
||||
let errorApi: ErrorApi;
|
||||
|
||||
beforeEach(() => {
|
||||
errorApi = { post: jest.fn() };
|
||||
errorApi = { post: jest.fn(), error$: jest.fn() };
|
||||
apis = ApiRegistry.from([
|
||||
[lighthouseApiRef, new LighthouseRestApi('http://lighthouse')],
|
||||
[errorApiRef, errorApi],
|
||||
|
||||
Reference in New Issue
Block a user