英文:
Why Angular code is not going in catch block if router.navigate is throwing the error?
问题
try {
this._router.navigate([result?.data?.menuLink]);
console.log('inside try block');
} catch {
this._router.navigate(['/dashboards/analytics']);
console.log('inside catch block');
}
在try块中的router.navigate
抛出错误,因为该路径不存在,但它没有进入catch块。
控制台中显示以下错误:
core.mjs:6469 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'config/payment'
英文:
try {
this._router.navigate([result?.data?.menuLink]);
console.log('inside try block');
} catch {
this._router.navigate(['/dashboards/analytics']);
console.log('inside catch block');
}
The router.navigate
in try block is throwing error because that path does not exist but it is not going inside the catch block.
I am getting below error in console:
core.mjs:6469 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'config/payment'
答案1
得分: 1
只需要为捕捉 Promise 错误设置 async await
语法。
constructor(private _router: Router) {
this.catchRouteError()
}
async catchRouteError() {
try {
await this._router.navigate([result?.data?.menuLink]);
console.log('inside try block');
} catch {
this._router.navigate(['/dashboards/analytics']);
console.log('inside catch block');
}
}
但根据您的代码和描述,您可以为清晰的代码设置一个特定的组件或在路由器中使用重定向配置。
const routes: Routes = [
{
path: 'products',
component: ProductsComponent
},
{
path: 'cart',
component: CartComponent
},
{ path: '', redirectTo: '/products', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
];
英文:
just need set a syntax async await
for catch promise error
constructor(private _router: Router) {
this.catchRouteError()
}
async catchRouteError() {
try {
await this._router.navigate([result?.data?.menuLink]);
console.log('inside try block');
} catch {
this._router.navigate(['/dashboards/analytics']);
console.log('inside catch block');
}
}
But according to your code and description, you can set a specific component or use redirect config in your router for clean code
const routes: Routes = [
{
path: 'products',
component: ProductsComponent
},
{
path: 'cart',
component: CartComponent
},
{ path: '', redirectTo: '/products', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
];
答案2
得分: 1
根据文档,此函数返回一个Promise。Promises(承诺)是异步的,这意味着在你尝试捕获错误时,错误尚未发生。相反,你可以在 promise 上使用.catch()
函数。
this._router.navigate([result?.data?.menuLink])
.catch(() => {
this._router.navigate(['/dashboards/analytics']);
console.log('inside catch block');
})
英文:
According to the docs, the function returns a Promise. Promises are asynchronous, which means at the time when you are trying to catch the error, the error has not happened yet. Instead, you can use the .catch()
function on the promise.
this._router.navigate([result?.data?.menuLink])
.catch(() => {
this._router.navigate(['/dashboards/analytics']);
console.log('inside catch block');
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论