W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
系統(tǒng)在處理用戶請求時,會遇到各種各樣的錯誤情況。如:系統(tǒng)內(nèi)部錯誤,url 不存在,沒有權(quán)限,服務(wù)不可用等,這些情況下需要給用戶顯示對應(yīng)的錯誤頁面。
通過 thinkjs
命令創(chuàng)建項目時,會自動添加錯誤處理的邏輯文件以及相應(yīng)的錯誤頁面。
錯誤邏輯文件路徑為 src/common/controller/error.js
,該文件內(nèi)容大致如下:
"use strict";
/**
* error controller
*/
export default class extends think.controller.base {
/**
* display error page
* @param {Number} status []
* @return {Promise} []
*/
displayErrorPage(status){
let module = "common";
if(think.mode !== think.mode_module){
module = this.config("default_module");
}
let file = `${module}/error/${status}.html`;
let options = this.config("tpl");
options = think.extend({}, options, {type: "ejs"});
return this.display(file, options);
}
/**
* Bad Request
* @return {Promise} []
*/
_400Action(){
return this.displayErrorPage(400);
}
/**
* Forbidden
* @return {Promise} []
*/
_403Action(){
return this.displayErrorPage(403);
}
/**
* Not Found
* @return {Promise} []
*/
_404Action(){
return this.displayErrorPage(404);
}
/**
* Internal Server Error
* @return {Promise} []
*/
_500Action(){
return this.displayErrorPage(500);
}
/**
* Service Unavailable
* @return {Promise} []
*/
_503Action(){
return this.displayErrorPage(503);
}
}
對應(yīng)的模版文件路徑為 view/common/error_{Number}.html
。
系統(tǒng)默認(rèn)支持的錯誤類型有 400
,403
,404
,500
和 503
。
錯誤的請求,如:惡意構(gòu)造一些非法的數(shù)據(jù)訪問、訪問的 url 不合法等。
當(dāng)前訪問沒有權(quán)限。
訪問的 url 不存在。
系統(tǒng)內(nèi)部出現(xiàn)錯誤,導(dǎo)致當(dāng)前請求不可用。
服務(wù)不可用,需要等到恢復(fù)后才能訪問。
項目里可以根據(jù)需要擴(kuò)展錯誤類型,假如添加一個項目特有的錯誤 600
,那么可以通過下面步驟進(jìn)行:
在 src/common/controller/error.js
文件中,合適的位置添加如下的代碼:
_600Action(){
return this.displayErrorPage(600);
}
添加文件 view/common/error_600.html
,并在文件里添加顯示的錯誤內(nèi)容。
添加完錯誤后,需要在對應(yīng)地方調(diào)用顯示錯誤才能讓用戶看到,可以通過 think.statusAction
方法實現(xiàn)。如:
export default class extends think.controller.base {
indexAction(){
if(someError){
return think.statusAction(600, this.http); //顯示 600 錯誤,需要將 http 對象傳遞進(jìn)去
}
}
}
修改錯誤頁面樣式,只需要修改對應(yīng)的模版文件即可,如:修改 404
錯誤則修改模版文件view/common/error_404.html
。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: