本文實(shí)例講述了laravel5框架自定義錯(cuò)誤頁(yè)面配置操作。分享給大家供大家參考,具體如下:
背景
- 最近試著學(xué)習(xí) laravel 5.5,使用 composer 下載新的框架源代碼
1
|
composer create-project --prefer-dist laravel/laravel lar5pro 5.5.* |
- 發(fā)現(xiàn)在輸入錯(cuò)誤的鏈接時(shí),會(huì)有如下的提示信息:
-
想到,一般成型的網(wǎng)站都會(huì)自定義404、501、503等頁(yè)面,所以通過(guò)網(wǎng)上搜索方法,進(jìn)行測(cè)試,可推薦如下的實(shí)現(xiàn)過(guò)程 …
框架: laravel 5.5
操作
①. 解釋
-
所有異常錯(cuò)誤都由類 app\exceptions\handler 處理,該類包含兩個(gè)方法:
report
和render
,其中的render
方法會(huì)將異常渲染到 http 響應(yīng)中
②. render 方法優(yōu)化
- 參考了網(wǎng)上的相關(guān)介紹,發(fā)現(xiàn)可以將 app\exceptions\handler 中的 render 方法修改為下面的樣子:
1
2
3
4
5
6
7
8
9
10
11
|
public function render( $request , exception $exception ) { /* 錯(cuò)誤頁(yè)面 */ if ( $exception ) { //todo laravel5.5 框架中 exception 類不存在 getstatuscode()方法,或許只能支持前面的版本! //$code = $exception->getstatuscode(); $code = flattenexception::create( $exception )->getstatuscode(); return response()->view( 'error.' . $code , [], $code ); } return parent::render( $request , $exception ); } |
【分析】
經(jīng)過(guò)對(duì)框架源碼的查看發(fā)現(xiàn),我們是通過(guò)實(shí)例化
flattenexception
類來(lái)獲得請(qǐng)求狀態(tài)碼的,根據(jù)提供的測(cè)試類flattenexceptiontest
,從而得出了上述的代碼,建議可以閱讀下源代碼以做比較
③. 創(chuàng)建 view 頁(yè)面
-
在
resources/views/error/
目錄下創(chuàng)建錯(cuò)誤頁(yè)面 - 命名格式為 {error.code}.blade.php
④. 訪問(wèn)測(cè)試
-
舉例來(lái)講,在
404.blade.php
中編輯設(shè)計(jì)自己的 404頁(yè)面 - 通過(guò)訪問(wèn)一個(gè)不存在的路由,以本人為例,顯示效果如下:
- 默認(rèn)如果數(shù)據(jù)處理有錯(cuò),是 500 異常報(bào)錯(cuò),此時(shí)可以通過(guò) debug 查看并進(jìn)行排錯(cuò)處理…
附錄
- 根據(jù)上面的操作,可擴(kuò)展創(chuàng)建其他錯(cuò)誤頁(yè)面
-
此處附錄一下
404.blade.php
源代碼,僅做參考
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
<!doctype html> <html lang= "en" > <head> <meta charset= "utf-8" > <title>404頁(yè)面</title> <style> #box{ margin: 0 auto; width: 540px; height: 540px; } p{ margin-bottom: 60px; width: 540px; height: 20px; text-align: center; line-height: 20px; } #mes{ font-size: 30px; color: red; } .hint{ color: #999; } a{ color: #259aea; text-decoration:none } </style> <script> var i = 5; var intervalid = setinterval( "fun()" , 1000); function fun() { if (i == 0) { window.location.href = "/" ; clearinterval(intervalid); } document.getelementbyid( "mes" ).innerhtml = i; i--; } </script> </head> <body> <div id= "box" > <img src= "{{ asset('images/error/404.jpg') }}" alt= "404" > <p>將在 <span id= "mes" >5</span> 秒鐘后返回 <a href= "{{ url('/') }}" rel= "external nofollow" >首頁(yè)</a></p> <p class = "hint" >非常抱歉 - 您可能輸入了錯(cuò)誤的網(wǎng)址,或者該網(wǎng)頁(yè)已刪除或移動(dòng)</p> </div> </body> </html> |
希望本文所述對(duì)大家基于laravel框架的php程序設(shè)計(jì)有所幫助。
原文鏈接:https://blog.csdn.net/u011415782/article/details/78794522