emberjs / emberjs/ember.js

Error when using replaceWith over a catch-all route

Open
#18,515 2 comments 0 reactions 0 assignees View on GitHub
Routing
Dominant language
TypeScript
Stars
22.6k
Forks
4.2k
Avg merge
3d 12h
Merged PRs (30d)
15

Description

In this scenario, I'm trying to achieve a "404" route to display a proper message. This is done via this pattern in the router:

```js
this.route("not_found", { path: "/*:unknown" });
```
So far so good. Then I'd like any route that tries to access a non-existing record (i.e. ajax getting 404 responses) to redirect to the same "not found" route, to achieve a unified UX. The only way I found to do this is by adding the following in the application route's `error` action handler:

```js
error(err, transition) {
let router = this.get("router");
if (err.errors && err.errors[0].status === "404") {
transition.abort();
return later(function() {
let transition_name = transition.to.name;
let url = router.urlFor(transition_name, transition.to.params);
return router.replaceWith("not_found", url);
});
}
},
```

However, this does not always work. Since the transition URL starts with a slash, the error we're getting is pretty weird:
```
history_location.js:223 Uncaught DOMException: Failed to execute 'replaceState' on 'History': A history state object with URL 'http://items/2' cannot be created in a document with origin 'http://localhost:4200' and URL 'http://localhost:4200/items/2'.
```

Fixing it works by adding the following after the call to `urlFor`:

```js
if (url.startsWith("/")) {
url = url.substr(1);
}
```

Reproduction repo: https://github.com/vmalloc/ember-bug-18515 (note - the repo is *with* the workaround)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.