未找到解析数据时,UI路由器转换为404状态

时间:2015-08-05 15:49:42

标签: javascript angularjs angular-ui-router

当您无法通过状态参数解析数据(状态参数无效或过时)时,转换到404状态的好方法是什么。我当前通过抛出异常并在全局事件处理程序中处理它来完成它:

$stateProvider.state('main.tasks.record', {
  url: '/task/{id}',
  resolve: {
    task: function (Tasks, $stateParams) {
      var task = Tasks.findOne($stateParams.id);
      if (!task) {
         throw new Error('Task with id "' + $stateParams.id + '" not found');
      }
    }
  }
});

$rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams, error) {
    if (error.message.match('not found')) {
      console.log('Not found error detected', error.message);
      console.log('Redirecting to main state');
      return $state.go('main');
    }

    //all other exceptions - log and rethrow
    event.preventDefault();
    console.log('$stateChangeError');
    console.log(arguments);
    throw 'Error while change states: from ' + fromState.name + ' to ' + toState.name;
});

有没有更好的方法呢?

1 个答案:

答案 0 :(得分:0)

您可以使用URL路由器路由到捕获状态:

$urlRouterProvider.otherwise('/fourOFour');
$stateProvider.state("fourOFour", { url : '/fourOFour'//...});