laravelÔõôÌøתµ½404
laravel ÊÇÒ»¿îÊܽӴýµÄ php ¿ª·¢¿ò¼Ü£¬¿ÉÒÔÇáËɹ¹½¨¸ßЧµÄ web Ó¦ÓóÌÐò¡£ ÔÚ½¨ÉèÓ¦ÓóÌÐòʱ£¬Äú¿ÉÄÜ»áÓöµ½Ðí¶à http ¹ýʧ£¬ÀýÈç 404 ¹ýʧ. ±¾ÎĽ«ÖصãÏÈÈÝÔõÑù½« laravel Ó¦ÓóÌÐòÖеÄÁ÷Á¿Öض¨Ïòµ½×Ô½ç˵ 404 ¹ýʧҳÃæ¡£
Laravel ĬÈÏÌṩÁËÒ»¸ö¼òÆ 404 ¹ýʧҳÃ棬¸ÃÒ³ÃæÖ»°üÀ¨Ò»Ìõ¼òÆÓµÄÐÂÎÅ£º¡°Î´ÕÒµ½¡±¡£ ËäÈ»Õâ¹ØÓÚ¼òÆÓµÄÍøÕ¾×ã¹»ÁË£¬µ«ÈôÊÇÄúµÄÓ¦ÓóÌÐòÐèÒª¾ßÓиü¶àרҵÐԺ͸öÐÔ»¯ÄÚÈÝ£¬Äú¿ÉÄÜÐèÒª×Ô½ç˵ 404 ¹ýʧҳÃæ¡£
ÓÐÁ½ÖÖÒªÁì¿ÉÒÔ×Ô½ç˵ Laravel µÄ 404 ¹ýʧҳÃ棺ʹÓà Lumen ºÍʹÓà Laravel¡£ ÔÚ±¾ÕÂÖУ¬ÎÒÃǽ«ÏÈÈÝÔõÑùʹÓà Laravel ×Ô½ç˵ 404 ¹ýʧҳÃæ¡£
ÔÚ Laravel ÖУ¬¿ÉÒÔͨ¹ý´¦Àí³ÌÐòÍê³ÉÈκΠHTTP ¹ýʧ£¬°üÀ¨ 404 ¹ýʧ¡£ Õâ¾ÍÊÇΪʲôÔÚÐÞ¸Ä 404 ¹ýʧҳÃæ֮ǰ£¬ÐèÒªÔÚ Laravel Ó¦ÓóÌÐòÖÐ×¢²á×Ô½ç˵¹ýʧ´¦Àí³ÌÐòµÄÔµ¹ÊÔÓÉ¡£
µÚÒ»²½ÊÇ·¿ª App\Exceptions\Handler.php Îļþ£¬ÕÒµ½ render ÒªÁì¡£ÕâÊÇʹÃüµÄ½¹µã´úÂ룬ËüÈÏÕæäÖȾ¸ø¶¨µÄÒì³£¡£Ä¬ÈÏÇéÐÎÏ£¬Laravel ʹÓà 404 ÊÓͼÎļþäÖȾ 404 ¹ýʧ¡£Òò´Ë£¬ÎÒÃÇ¿ÉÒÔÁýÕÖ´ËÒªÁ죬²¢ÔÚÆäÖбàд´úÂëÒÔ·ºÆð×Ô½ç˵ 404 Ò³Ãæ¡£
ÒÔÏÂÊÇÁýÕÖ render ÒªÁìÒÔ´¦Àí 404 ¹ýʧ²¢½«ÆäÖض¨Ïòµ½×Ô½ç˵ҳÃæµÄʾÀý´úÂ룺
public function render($request, Exception $exception) { if ($exception instanceof ModelNotFoundException && $request->wantsJson()) { return response()->json([ 'error' => 'Resource not found' ], 404); } if ($exception instanceof NotFoundHttpException) { return response()->view('errors.404', [], 404); } return parent::render($request, $exception); }
µÇ¼ºó¸´ÖÆ
ÔÚ´Ë´úÂëÖУ¬ÎÒÃÇÊ×ÏÈÌí¼ÓÁËÒ»ÖÖÇéÐΣ¬ÈôÊÇÇëÇóµÄ×ÊÔ´²»ÊÇÄ£×Ó£¬Ôò·µ»Ø×Ô½ç˵ JSON ÃûÌõĹýʧÐÂÎÅ¡£ È»ºó£¬ÎÒÃÇÌí¼ÓÁíÒ»¸öÌõ¼þ£¬ÈôÊDZ¬·¢ NotFoundHttpException ¹ýʧ£¬ÎÒÃǽ«Öض¨Ïòµ½×Ô½ç˵ 404 ÊÓͼÎļþ¡£
Ö÷ÒªµÄÊÇÒª¼Ç×Å£¬ÎÒÃÇÐèÒªÔÚ resources/views/errors Ŀ¼Öн¨Éè×Ô½ç˵ 404 ÊÓͼÎļþ£¬ÒÔ±ã Laravel ¿ÉÒÔ׼ȷ·ºÆð×Ô½ç˵ҳÃæ¡£ ½ñÊÀÂëÖеÄÒì³£´¦Àí³ÌÐò¼ì²âµ½ 404 ¹ýʧʱ£¬Ëü½«Öض¨Ïòµ½´ËÎļþ¾ÙÐÐäÖȾ¡£
³ýÁË×Ô½ç˵ 404 Ò³ÃæÖ®Í⣬Äú»¹¿ÉÒÔ×Ô½ç˵ÆäËû HTTP ¹ýʧҳÃ棬ÀýÈç 403¡¢500 »ò 503 Ò³Ãæ¡£ Ö»ÐèʹÓÃÏàͬµÄÒªÁ죬µ«ÏìÓ¦µØ¸ü¸ÄÒì³£´¦Àí³ÌÐòÖеÄÌõ¼þ¼´¿É¡£
×ܽá
ÔÚ¿ª·¢ Laravel Ó¦ÓóÌÐòʱ£¬´¦Àí³£¼ûµÄ HTTP ¹ýʧ£¨ÀýÈç 404 ¹ýʧ£©ÊÇÖÁ¹ØÖ÷ÒªµÄ¡£ ÔÚ±¾ÎÄÖУ¬ÎÒÃÇÏàʶÁËÔõÑùʹÓà Laravel ×Ô½ç˵ 404 ¹ýʧҳÃ棬°üÀ¨±àд×Ô½ç˵Òì³£´¦Àí³ÌÐòºÍÊÓͼÎļþ¡£Í¨¹ý×Ô½ç˵ 404 ¹ýʧҳÃ棬Äú¿ÉÒÔÇáËÉÓÅ»¯Óû§ÌåÑ飬²¢Ìá¸ßÓ¦ÓóÌÐòµÄ¿ÉÓÃÐÔ¡£
ÒÔÉϾÍÊÇlaravelÔõôÌøתµ½404µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡