mirror of
https://github.com/angular/angular
synced 2026-05-24 09:28:37 +00:00
refactor(core): Support Error like object for on resource errors.
Error like object will be treated as errors.
Related to #61861
(cherry picked from commit 835a643161)
This commit is contained in:
parent
96bb4c6ae3
commit
84f397c831
2 changed files with 36 additions and 2 deletions
|
|
@ -6,7 +6,7 @@
|
|||
* found in the LICENSE file at https://angular.dev/license
|
||||
*/
|
||||
|
||||
import {of, Observable, BehaviorSubject} from 'rxjs';
|
||||
import {of, Observable, BehaviorSubject, throwError} from 'rxjs';
|
||||
import {TestBed} from '../../testing';
|
||||
import {ApplicationRef, Injector, signal} from '../../src/core';
|
||||
import {rxResource} from '../src';
|
||||
|
|
@ -88,6 +88,31 @@ describe('rxResource()', () => {
|
|||
});
|
||||
await appRef.whenStable();
|
||||
});
|
||||
|
||||
it('should handle Error like objects', async () => {
|
||||
class FooError implements Error {
|
||||
name = 'FooError';
|
||||
message = 'This is a FooError';
|
||||
}
|
||||
|
||||
const injector = TestBed.inject(Injector);
|
||||
const appRef = TestBed.inject(ApplicationRef);
|
||||
|
||||
const sig = signal(1);
|
||||
const observable = throwError(() => new FooError());
|
||||
|
||||
const rxRes = rxResource({
|
||||
params: sig,
|
||||
stream: () => observable,
|
||||
injector: injector,
|
||||
});
|
||||
|
||||
await appRef.whenStable();
|
||||
|
||||
expect(rxRes.error()).toBeInstanceOf(FooError);
|
||||
|
||||
expect(() => rxRes.value()).toThrowError(/This is a FooError/);
|
||||
});
|
||||
});
|
||||
|
||||
async function waitFor(fn: () => boolean): Promise<void> {
|
||||
|
|
|
|||
|
|
@ -493,13 +493,22 @@ function createDebugNameObject(
|
|||
}
|
||||
|
||||
export function encapsulateResourceError(error: unknown): Error {
|
||||
if (error instanceof Error) {
|
||||
if (isErrorLike(error)) {
|
||||
return error;
|
||||
}
|
||||
|
||||
return new ResourceWrappedError(error);
|
||||
}
|
||||
|
||||
export function isErrorLike(error: unknown): error is Error {
|
||||
return (
|
||||
error instanceof Error ||
|
||||
(typeof error === 'object' &&
|
||||
typeof (error as Error).name === 'string' &&
|
||||
typeof (error as Error).message === 'string')
|
||||
);
|
||||
}
|
||||
|
||||
class ResourceValueError extends Error {
|
||||
constructor(error: Error) {
|
||||
super(
|
||||
|
|
|
|||
Loading…
Reference in a new issue