How to handle error in a Resolver

前端 未结 3 1917
旧巷少年郎
旧巷少年郎 2021-01-30 10:46

I\'m trying to use resolvers in order to make a better UX. Everything works great on the happy path. What I can\'t seem to figure out is how to handle exceptions. My resolver ca

3条回答
  •  不要未来只要你来
    2021-01-30 11:14

    I only wanted to provide a very similar updated answer but with some updated code. I personally think the error should simply not be managed inside the resolver.

    Why? Well, I think that the resolver's job is to resolve, not to figure out what to do if it can't resolve. We might be using this resolver in two or three different components, and each of them might decide to react in a different way if the resolver fails. We might want to redirect in one of them to a 404 page, but in other maybe we just try to fix graciously the error by displaying something else.

    Sure, we might also want to react differently depending on what error we get: maybe the user was not authorised, or maybe that item was deleted or didn't even exist on the first place, who knows. We might want to display different results and in that case I totally upvote DeborahK's updated answer. But for most cases, I think that overcomplicates the matter (an extra interface only for the resolver, making sure the error inside it's descriptive...) and that we probably won't really care why the resolver failed: it just did, let the component that needed that item figure out what to do, and move on.

    import { Injectable } from '@angular/core';
    import { ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router';
    import { Observable, of } from 'rxjs';
    import { catchError } from 'rxjs/internal/operators';
    import { Product } from '../_interfaces';
    import { ProductsService } from '../_services';
    
    @Injectable()
    export class ProductResolver implements Resolve {
    
        constructor(private productsService: ProductsService) {
        }
    
        public resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable {
            const id = route.paramMap.get('id');
            return this.productsService.getProduct(id).pipe(
                catchError(error => {
                    console.error(`Can't resolve product with id ${id} because of the error:`);
                    console.error(error);
                    return of(null);
                })
            );
        }
    }
    

提交回复
热议问题