# 錯誤處理
[TOC=2,3]
系統在處理用戶請求時,會遇到各種各樣的錯誤情況。如:系統內部錯誤,url 不存在,沒有權限,服務不可用等,這些情況下需要給用戶顯示對應的錯誤頁面。
## 錯誤頁面
通過?`thinkjs`?命令創建項目時,會自動添加錯誤處理的邏輯文件以及相應的錯誤頁面。
錯誤邏輯文件路徑為?`src/common/controller/error.js`,該文件內容大致如下:
~~~
"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);
}
}
~~~
對應的模版文件路徑為?`view/common/error_{Number}.html`。
## 錯誤類型
系統默認支持的錯誤類型有?`400`,`403`,`404`,`500`?和?`503`。
#### 400
錯誤的請求,如:惡意構造一些非法的數據訪問、訪問的 url 不合法等。
#### 403
當前訪問沒有權限。
#### 404
訪問的 url 不存在。
#### 500
系統內部出現錯誤,導致當前請求不可用。
#### 503
服務不可用,需要等到恢復后才能訪問。
## 擴展錯誤類型
項目里可以根據需要擴展錯誤類型,假如添加一個項目特有的錯誤?`600`,那么可以通過下面步驟進行:
#### 1、添加 _600Action
在?`src/common/controller/error.js`?文件中,合適的位置添加如下的代碼:
~~~
_600Action(){
return this.displayErrorPage(600);
}
~~~
#### 2、添加錯誤頁面
添加文件?`view/common/error_600.html`,并在文件里添加顯示的錯誤內容。
#### 3、顯示錯誤頁面
添加完錯誤后,需要在對應地方調用顯示錯誤才能讓用戶看到,可以通過?`think.statusAction`?方法實現。如:
~~~
export default class extends think.controller.base {
indexAction(){
if(someError){
return think.statusAction(600, this.http); //顯示 600 錯誤,需要將 http 對象傳遞進去
}
}
}
~~~
## 修改錯誤頁面樣式
修改錯誤頁面樣式,只需要修改對應的模版文件即可,如:修改?`404`?錯誤則修改模版文件`view/common/error_404.html`。
- 快速入門
- 介紹
- 創建項目
- 項目結構
- 代碼規范
- 升級指南
- 進階應用
- 模塊
- 控制器
- 視圖
- 配置
- 路由
- 模型
- 介紹
- 事務
- 關聯模型
- Mysql
- MongoDB
- SQLite
- Adapter
- 介紹
- Cache
- Session
- WebSocket
- Template
- 擴展功能
- thinkjs 命令
- 靜態資源訪問
- Middleware
- Service
- Cookie
- 錯誤處理
- 錯誤信息
- 數據校驗
- 國際化
- 路徑常量
- REST API
- 定時任務
- 線上部署
- 推薦模塊
- API
- think
- think.base
- think.http.base
- http
- controller
- rest controller
- model
- model.mongo
- middleware