Sub topic 13
Handling resolver failures
This chapter assumes you can write a basic ResolveFn and read resolved data in a component. It also assumes you are comfortable with RxJS operators such as catchError, retry, and of. Here you will see what the router does when a resolver fails, and how to turn that failure into a deliberate outcome.
What happens when a resolver fails
A resolver runs before the route activates, so a failure there blocks the whole navigation. If the resolver throws or its Observable errors, the router:
- Cancels the navigation with a
NavigationErrorevent. - Leaves the user on the page they were already on. The URL does not change.
- Passes the error to the router's error handler, which by default rejects the promise returned by
router.navigate()orrouter.navigateByUrl().
For a user who clicked a link, nothing visibly happens. There is no error page and no message, and the only trace is an unhandled promise rejection in the console. The failed navigation also leaves no history entry, so the user can't go back to it.
A second failure mode produces no error at all. If a resolver's Observable completes without emitting a value, the router cancels the navigation silently (a NavigationCancel event, not a NavigationError). This usually comes from an operator such as filter or takeUntil that discards every value.
Choosing a failure strategy
You have four options. The right one depends on whether the page can work without the data.
| Strategy | Use when | Result for the user |
|---|---|---|
| Redirect with `RedirectCommand` | The page is meaningless without the data (a missing product, no permission) | Lands on a not-found or error page |
| Fallback value | The page can show an empty or degraded state | Page opens, component renders the fallback |
| Retry, then one of the above | The failure is probably temporary (network blip, 503) | Short delay, then success or a final outcome |
| Global navigation error handler | You want logging or reporting for every failure | No change in behavior by itself |
The first three go inside the resolver. The last is configured once on the router.
Redirecting with RedirectCommand
From Angular 18, a resolver can return a RedirectCommand instead of data. The router cancels the current navigation and starts a new one to the UrlTree inside the command. This is the resolver counterpart of returning a UrlTree from a guard.
import { HttpErrorResponse } from '@angular/common/http';
import { inject } from '@angular/core';
import { RedirectCommand, ResolveFn, Router } from '@angular/router';
import { catchError, of } from 'rxjs';
import { Product, ProductService } from './product.service';
export const safeProductResolver: ResolveFn<Product | RedirectCommand> = (route) => {
const router = inject(Router);
const id = route.paramMap.get('id')!;
return inject(ProductService).getById(id).pipe(
catchError((err: HttpErrorResponse) => {
const target = err.status === 404 ? '/not-found' : '/error';
return of(new RedirectCommand(router.parseUrl(target)));
}),
);
};Three details matter here:
- The return type is
Product | RedirectCommand. ARedirectCommandis never delivered to the component. The router consumes it, so the component'sproductinput is still typedProduct. catchErrormust return an Observable, so the command is wrapped inof(...). Returning the command directly from the callback is a type error.RedirectCommandaccepts a second argument of navigation options, for example{ skipLocationChange: true }. That keeps the failing URL in the address bar while the error page renders.
Returning a fallback value
If the page can render without the data, resolve to a safe default and let the component show an empty state. Resolve to a value that makes the failure visible, not to a fake success.
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { catchError, map, of } from 'rxjs';
import { Review, ReviewService } from './review.service';
export interface ReviewsResult {
reviews: Review[];
failed: boolean;
}
export const reviewsResolver: ResolveFn<ReviewsResult> = (route) =>
inject(ReviewService).forProduct(route.paramMap.get('id')!).pipe(
map((reviews) => ({ reviews, failed: false })),
catchError(() => of({ reviews: [], failed: true })),
);The failed flag lets the template distinguish "no reviews yet" from "reviews could not be loaded". Without it, an outage looks like an empty list.
Retrying before giving up
Retries belong before catchError, so the fallback or redirect applies only after the retries are used up. The retry operator accepts a delay in milliseconds.
import { HttpErrorResponse } from '@angular/common/http';
import { inject } from '@angular/core';
import { RedirectCommand, ResolveFn, Router } from '@angular/router';
import { catchError, of, retry, throwError, timer } from 'rxjs';
import { Product, ProductService } from './product.service';
export const resilientProductResolver: ResolveFn<Product | RedirectCommand> = (route) => {
const router = inject(Router);
return inject(ProductService).getById(route.paramMap.get('id')!).pipe(
retry({
count: 2,
delay: (err: HttpErrorResponse, attempt) =>
err.status >= 500 ? timer(attempt * 500) : throwError(() => err),
}),
catchError(() => of(new RedirectCommand(router.parseUrl('/error')))),
);
};The delay function receives the error and the attempt number. It returns a timer for server errors (500 and above) and rethrows everything else immediately. Retrying a 404 or 403 only makes the user wait longer for the same answer.
Logging every failure globally
Per-resolver handling covers the failures you anticipated. A router-level handler catches the rest, including errors thrown in guards and in lazy-load imports. Register it with withNavigationErrorHandler.
import { ApplicationConfig, inject } from '@angular/core';
import { provideRouter, withNavigationErrorHandler } from '@angular/router';
import { routes } from './app.routes';
import { ErrorReporter } from './error-reporter';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(
routes,
withNavigationErrorHandler((navigationError) => {
inject(ErrorReporter).report(navigationError.error, navigationError.url);
}),
),
],
};The handler runs in an injection context, so inject() works. Use it for reporting. Handle user-facing outcomes (redirects, fallbacks) in the resolver, where you know what the failed request was for.
Common mistakes
- Swallowing the error with
EMPTY.catchError(() => EMPTY)completes without emitting, so the navigation is cancelled silently. The user sees nothing and you see no error. - Putting
catchErrorbeforeretry. The error is already converted to a value, soretrynever sees a failure. - Redirecting to a route that has the same resolver. If
/erroralso loads data through a failing resolver, you create a redirect loop. Keep error pages free of resolvers. - Treating the fallback as real data. An empty array that means "the request failed" is indistinguishable from a genuinely empty result. Carry a flag or use a discriminated type.
Checking your understanding
Exercise
A resolver contains getById(id).pipe(catchError(() => EMPTY)). A user opens a product URL while the API is down. What does the user experience, and what would you change?
Show answer
EMPTY completes without emitting a value, so the router cancels the navigation without raising an error. The user stays on the current page, the URL does not change, and nothing is logged as a failure. Replace EMPTY with of(new RedirectCommand(router.parseUrl('/error'))) (and widen the return type to Product | RedirectCommand), or resolve to a fallback value the component can display.
Exercise
Why should retry come before catchError in a resolver, and why should the retry delay function rethrow 4xx errors instead of retrying them?
Show answer
catchError turns the error into a normal value, so a retry placed after it never sees an error and never runs. Placing retry first means the fallback or redirect applies only after the retries fail. 4xx errors such as 404 or 403 are not temporary, so retrying only delays the final outcome and keeps the user waiting.