Skip to content

Commit 08b9452

Browse files
JeanMechethePunderWoman
authored andcommitted
fix(core): Ensure resource sets an error (#58855)
Before this commit, a resource with a previous value wouldn't set the error state correctly. This commit fixes this. A resource will set its status to error even when there was a previous valid value. PR Close #58855
1 parent beec896 commit 08b9452

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

packages/core/src/resource/resource.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,8 +115,9 @@ abstract class BaseWritableResource<T> implements WritableResource<T> {
115115
* Put the resource into the error state.
116116
*/
117117
protected setErrorState(err: unknown): void {
118-
this.status.set(ResourceStatus.Error);
119118
this.value.set(undefined);
119+
// The previous line will set the status to `Local`, so we need to update it.
120+
this.status.set(ResourceStatus.Error);
120121
this.error.set(err);
121122
}
122123

packages/core/test/resource/resource_spec.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,10 +128,45 @@ describe('resource', () => {
128128

129129
expect(echoResource.status()).toBe(ResourceStatus.Error);
130130
expect(echoResource.isLoading()).toBeFalse();
131+
expect(echoResource.hasValue()).toBeFalse();
131132
expect(echoResource.value()).toEqual(undefined);
132133
expect(echoResource.error()).toBe('Something went wrong....');
133134
});
134135

136+
it('should expose errors on reload', async () => {
137+
const backend = new MockEchoBackend();
138+
const counter = signal(0);
139+
const echoResource = resource({
140+
request: () => ({counter: counter()}),
141+
loader: (params) => {
142+
if (params.request.counter % 2 === 0) {
143+
return Promise.resolve('ok');
144+
} else {
145+
throw new Error('KO');
146+
}
147+
},
148+
injector: TestBed.inject(Injector),
149+
});
150+
151+
TestBed.flushEffects();
152+
await backend.flush();
153+
154+
expect(echoResource.status()).toBe(ResourceStatus.Resolved);
155+
expect(echoResource.isLoading()).toBeFalse();
156+
expect(echoResource.hasValue()).toBeTrue();
157+
expect(echoResource.value()).toEqual('ok');
158+
expect(echoResource.error()).toBe(undefined);
159+
160+
counter.update((value) => value + 1);
161+
TestBed.flushEffects();
162+
163+
expect(echoResource.status()).toBe(ResourceStatus.Error);
164+
expect(echoResource.isLoading()).toBeFalse();
165+
expect(echoResource.hasValue()).toBeFalse();
166+
expect(echoResource.value()).toEqual(undefined);
167+
expect(echoResource.error()).toEqual(Error('KO'));
168+
});
169+
135170
it('should _not_ load if the request resolves to undefined', () => {
136171
const counter = signal(0);
137172
const backend = new MockEchoBackend();

0 commit comments

Comments
 (0)