# 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

```javascript
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

```javascript
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`).

```javascript
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';
});
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://router5.js.org/advanced/errors-and-redirections.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
