在thinkphp5中如何拋出異常狀態碼(比如401,403,404等),因為這些能極大的給用戶以良好的體驗。
因為在上線階段,任何的系統錯誤信息都不能讓瀏覽用戶給看到,比如404(Not Found)頁面我們應該直接拋出一個404異常,最好是配合一個404頁面來展示出來,給用戶以最好的體驗,這是非常重要的。
要做到這一點,首先要在你的配置文件將調試模式關閉(在開發階段要打開):
|
1
|
'app_debug'
=> false,
|
然后在配置文件中配置404等頁面的模板路徑(APP_PATH指的是application路徑):
|
1
|
'http_exception_template'
=> [ 404 => APP_PATH.
'404.html'
, 403 => APP_PATH.
'404.html'
,]
|
404頁面部分代碼如下:
|
1
2
3
4
5
6
7
|
<
div
class
=
"bg"
>
<
div
class
=
"cont"
>
<
div
class
=
"c1"
><
img
src
=
"/public/static/404/01.png"
class
=
"img1"
/></
div
>
<
h2
><?
php
echo $e->getMessage()?>
<!--輸出拋出異常信息-->
</
h2
>
<
div
class
=
"c2"
><
a
href
=
"#"
class
=
"re"
>返回論壇</
a
><
a
href
=
"#"
class
=
"home"
>網站首頁</
a
><
a
href
=
"#"
class
=
"sr"
>搜索一下頁面相關信息</
a
></
div
>
<
div
class
=
"c3"
>您可能輸入了錯誤的網址,或者該網頁已刪除或移動,千鋒PHP</
div
>
</
div
></
div
>
|
下面來進行測試:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
if
(Request::instance()->isAjax()) {
$data
= input();
$info
= [];
$where
=
''
;
switch
(
$data
[
'msg'
]) {
case
'驗證碼'
:
$info
= [
'y'
=>
'輸入正確'
,
'n'
=>
'輸入錯誤'
,
];
$where
= session::get(
'admin_login_session'
) == md5(
$data
[
'param'
]);
break
;
}
if
(
$where
) {
echo
'{"info":"'
.
$data
[
'msg'
] .
$info
[
'y'
] .
'","status":"y"}'
;
//注意ValidForm返回格式(json)
}
else
{
echo
'{"info":"'
.
$data
[
'msg'
] .
$info
[
'n'
] .
'","status":"n"}'
;
//注意ValidForm返回格式(json)
}
}
else
{
throw
new
\think\exception\HttpException(403,
'~~~千鋒PHP通知您非法請求~~~'
);
//因為此處只能是ajax來訪問,當直接在瀏覽器中訪問該方法時,
可以拋出一個403,其他類似),此處有簡寫方法abort代替
}
|
