ThinkJS 錯誤處理

2021-09-17 14:26 更新

錯誤處理

系統(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)支持的錯誤類型有 400403,404500 和 503。

400

錯誤的請求,如:惡意構(gòu)造一些非法的數(shù)據(jù)訪問、訪問的 url 不合法等。

403

當(dāng)前訪問沒有權(quán)限。

404

訪問的 url 不存在。

500

系統(tǒng)內(nèi)部出現(xiàn)錯誤,導(dǎo)致當(dāng)前請求不可用。

503

服務(wù)不可用,需要等到恢復(fù)后才能訪問。

擴(kuò)展錯誤類型

項目里可以根據(jù)需要擴(kuò)展錯誤類型,假如添加一個項目特有的錯誤 600,那么可以通過下面步驟進(jìn)行:

1、添加 _600Action

在 src/common/controller/error.js 文件中,合適的位置添加如下的代碼:

  _600Action(){
    return this.displayErrorPage(600);
  }

2、添加錯誤頁面

添加文件 view/common/error_600.html,并在文件里添加顯示的錯誤內(nèi)容。

3、顯示錯誤頁面

添加完錯誤后,需要在對應(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。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號