[英]Catch (failed)net::ERR_NAME_NOT_RESOLVED in an Ember / Ember Data app
我正在開發一個使用 Ember Data 的 Ember 應用程序。 我們主要使用 Rails 和 Postgres 作為后端,但我們的一小部分數據存儲在 WordPress 后端。 WordPress 正在wp.example.com
上運行。
Ember Data 設置為與 Rails 和 WordPress 后端一起使用,所以我可以這樣做:
// Get WordPress category by slug
this.store.query('wordpress/category', { slug }).then((models) => {
// Leave page if no category was found
if (typeof models.get('firstObject') == 'undefined') this.transitionTo('backupRoute');
return models.get('firstObject');
});
現在我想知道如果wp
子域處於脫機狀態,我該如何捕捉錯誤。
當我更改 WordPress 后端 URL (我不確定這是否是模擬故障的最佳方法)時,我在 Chrome DevTools 中得到(failed)net::ERR_NAME_NOT_RESOLVED
,幾秒鍾后,Imber 顯示錯誤。想捕捉網絡錯誤並做一些有用的事情,在這種情況下,重定向。
有沒有辦法捕捉這些錯誤? 添加一個簡單的catch()
會完全破壞頁面。 當有一個待處理的請求時,它會保持白色約兩分鍾,然后顯示502 Bad Gateway 。 我也在日志中得到這個:
my_service_1 | (node:1) UnhandledPromiseRejectionWarning: [object Object]
my_service_1 | (node:1) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 13)
這個問題出現在今天的“我可以問一個問題”一集中。
這些代碼示例來自 Octane 風格的應用程序並具有 Octane 語法,但這些功能在舊版 Ember 中也可用。
一些內置的 Ember 功能將在這里為您提供幫助: 加載和錯誤子狀態以及錯誤事件。
首先,您需要拋出錯誤。 然后你需要添加一個錯誤動作,並說明發生錯誤時應該發生什么。 當您的請求出錯時,錯誤事件會自動觸發,您可以將轉換代碼放在那里。 錯誤事件處理是 Ember 路由的一個特性。
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
export default class ArticlesOverviewRoute extends Route {
@service store;
model(params) {
return this.store.query('wordpress/category', { slug }).then((models) => {
if (typeof models.get('firstObject') == 'undefined') {
throw new Error("Sorry, there was a problem")
};
});
}
@action
error(error, transition) {
this.transitionTo('backupRoute')
}
};
或者,如果您的目標是顯示錯誤頁面,您可以做一些更簡單的事情。 使用以下命令創建錯誤模板: ember g template error
。 這將創建一個模板文件app/templates/error.hbs
。 在模板中放入一些文本,例如“哎呀”。 所以你可以在它工作后看到它。
您仍然需要拋出錯誤以便 Ember 能夠注意到它,但您不再需要錯誤操作。 Ember 會自動路由到錯誤模板。
export default class ArticlesOverviewRoute extends Route {
@service store;
model(params) {
return this.store.query('wordpress/category', { slug }).then((models) => {
if (typeof models.get('firstObject') == 'undefined') {
throw new Error("Sorry, there was a problem")
};
});
}
};
錯誤模板可以存在於許多不同的路徑中。 指南包含所有詳細信息,但一般來說,您可以將它們放在路由文件夾中,例如some-route/error.hbs
或者您可以將它們放在應用程序的根目錄中,就像我們對ember g template error
所做的那樣
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.