---
order: 17
title: 錯誤處理
type: 進階
---
在用戶使用過程中,可能遇到各種異常情況,比如頁面 404,申請結果失敗,請求的返回異常等等,這篇文檔會按照報錯形式的不同,分別介紹下相應的處理建議。
## 頁面級報錯
### 應用場景
- 路由直接引導到報錯頁面,比如你輸入的網址沒有匹配到任何頁面,可以由路由引導到預設的 404 頁面。
- 代碼控制跳轉到報錯頁面,比如根據請求返回的數據,將沒有權限的用戶引導到 403 頁面。
### 實現
針對頁面級的報錯,我們提供了兩個業務組件供你選擇,可以很方便地實現一個報錯頁面:
- [Exception 異常頁](https://preview.pro.ant.design/exception/404)
```js
<Exception type="404" />
```
默認支持 404,403,500 三種錯誤,也可自定義文案等內容。
- [Result 結果頁](https://preview.pro.ant.design/result/fail)
```js
<Result
type="error"
title="提交失敗"
description="請核對并修改以下信息后,再重新提交。"
actions={
<Button size="large" type="primary">
返回修改
</Button>
}
/>
```
這個組件一般用在提交結果展示,文案操作等均可自定義。
## 提示性報錯
### 應用場景
- 表單項校驗報錯。
- 操作反饋。
- 網絡請求錯誤。
### 實現
關于表單項報錯,請參考 [antd Form](http://ant.design/components/form-cn/) 中的實現。對于操作反饋和網絡請求錯誤提示,有一些組件可能會用到:
- [Alert](http://ant.design/components/alert-cn/)
- [message](http://ant.design/components/message-cn/)
- [notification](http://ant.design/components/notification-cn/)
在單頁應用中,最常見的需求就是處理網絡錯誤信息,我們可以利用 message 和 notification 來吐出響應的接口/網絡/業務數據錯誤。
<img src="https://gw.alipayobjects.com/zos/rmsportal/cVTaurnfguplvNbctgBN.png" width="400" />
Ant Design Pro 封裝了一個強大的 `request.ts` 統一處理請求,提供了默認的錯誤處理以及提示。
```js
const checkStatus = response => {
if (response.status >= 200 && response.status < 300) {
return response;
}
const errortext = codeMessage[response.status] || response.statusText;
notification.error({
message: `請求錯誤 ${response.status}: ${response.url}`,
description: errortext,
});
const error = new Error(errortext);
error.name = response.status;
error.response = response;
throw error;
};
```
為了方便展示 404 等頁面,我們在 `request.ts` 中封裝了根據狀態跳轉到相應頁面的邏輯,建議在線上環境中刪除這個邏輯,代碼如下:
```js
.catch(e => {
const status = e.name;
if (status === 401) {
// @HACK
/* eslint-disable no-underscore-dangle */
window.g_app._store.dispatch({
type: 'login/logout',
});
return;
}
// environment should not be used
if (status === 403) {
router.push('/exception/403');
return;
}
if (status <= 504 && status >= 500) {
router.push('/exception/500');
return;
}
if (status >= 404 && status < 422) {
router.push('/exception/404');
}
});
```
完整代碼可參考:https://github.com/ant-design/ant-design-pro/blob/80ce8fe43746426abc054c1cf76b8f733f54b001/src/utils/request.ts