404 page in angular ui-router

I am using ui-router in an angular single page application. I have some routes defined, and I have a specific 404 route like this:

app.config(function($urlRouterProvider, $stateProvider){
      .state('example', {
         url: '/example/:id',
         templateUrl: 'example.html',
         controller: 'ExampleController'
      .state('404', {
         url: '*path',
         templateUrl: '404.html'

Notice how the url for 404 state is '*path', which means it will match any path. I made it so if the user types something like '/some-non-existent-url' he won't be redirected to '/404', but rather stay at '/some-non-existent-url', but see the 404.html template. Here comes the problem: say my app interacts with some REST API inside my ExampleController, and the API may return an object, or it may return 404 Not Found based on the id from the url it receives. So, inside my controller, whenever this happens, I try to redirect to 404:

app.controller('ExampleController', function($state){
    someAPICall().then(function(response){ // do something}, 
                            if(response.status == 404){

This is where the weird staff occurs. It displays the 404.html template - for a split second - and then redirects to home page (did not include it in my code here for the sake of brevity). My guess is that the '404' state does not have a real url specified: if I change it's url from '*path' to '/404' for example, this works fine, but I don't want to do this, as the user won't see which was the real url that caused a 404 response. Is there any workaround for this problem?


You have a mistake in your code. You are writing $urlProvider.otherwise('404'). Change it to $urlRouterProvider.otherwise('404'). That should get it working.

What worked for me was to remove $urlProvider.otherwise('404') and have the 404 state as the last state


 ? Is there a way to access resolved state dependencies besides injecting them into the controller?
 ? Cancel a $transitions change ui-router
 ? AngularJS - UI Router - flickering after check login
 ? Auth0 does not return user information immediately after creation
 ? How to avoid "polluting" the resolve method with ui-router
 ? how can i pass id to my ui-view
 ? Default route for angular ui router
 ? Angular-ui-router: ui-sref-active and nested states
 ? Is there a way to conditionally turn off reloadOnSearch in a controller?
 ? AngularJS UI-Router: preload $http data before app loads