router5
  • Read Me
  • Introduction
    • Why router5?
    • Getting Started
    • Ecosystem
    • Core concepts
    • Transition phase
  • Guides
    • Defining routes
    • Path Syntax
    • Router options
    • Navigating
    • In the browser
    • Observing state
  • Integration
    • With React
    • With Redux
  • Advanced
    • Plugins
    • Middleware
    • Preventing navigation
    • Errors and redirections
    • Dependency injection
    • Loading async data
    • Universal routing
    • Listeners plugin
  • API Reference
  • Migration
    • Migrating from 7.x to 8.x
    • Migrating from 6.x to 7.x
    • Migrating from 5.x to 6.x
    • Migrating from 4.x to 5.x
    • Migrating from 3.x to 4.x
    • Migrating from 2.x to 3.x
    • Migrating from 1.x to 2.x
    • Migrating from 0.x to 1.x
Powered by GitBook
On this page
  • Custom errors
  • A string
  • An object
  • Redirecting after an error
  1. Advanced

Errors and redirections

When failing a transition function (canActivate, canDeactivate, middleware) custom errors can be returned. Custom errors can be a string or an object and will be added to the error object and passed to start and navigate callbacks).

Custom errors

Custom errors can be a string (error code) or an object. They can be passed using the first argument of done callbacks or encapsulated in failed promises.

A string

router.canActivate('profile', (router) => (toState, fromState, done) => {
    done('my custom error');
});

router.navigate('profile', (err, state) => {
    /* Error:
    {
        code: 'CANNOT_ACTIVATE',
        segment: 'profile',
        error: 'my custom error'
    }
    /*
})

An object

router.canActivate('profile', (router) => (toState, fromState, done) => {
    done({
        why: 'because'
    });
});

router.navigate('profile', (err, state) => {
    /* Error:
    {
        code: 'CANNOT_ACTIVATE',
        segment: 'profile',
        why: 'because'
    }
    */
})

Redirecting after an error

When you fail a transition, you can pass a redirect property to specify what the router should do next. redirect must be an object containing the route name you want to redirect to (name) and optionally can contain params (params).

router.canActivate('profile', (router) => (toState, fromState, done) => {
    return isUserLoggedIn()
        .catch(() => Promise.reject({ redirect: { name: 'login' }}));
});

router.navigate('profile', (err, state) => {
    // err is null
    state.name === 'login';
});
PreviousPreventing navigationNextDependency injection

Last updated 6 years ago