laravel ¹ýʧÌøת
×÷ΪһÃû laravel ¿ª·¢Õߣ¬ÎÒÃǾ³£»áÓöµ½ÖÖÖÖ¹ýʧ¡£ÓÐЩÊÇÓÉ´úÂë¹ýʧÒýÆðµÄ£¬ÓÐЩÔòÊÇÓÉÓÚÓû§ÊäÈ벻׼ȷ»ò²Ù×÷²»µ±ÒýÆðµÄ¡£µ±ÕâЩ¹ýʧ±¬·¢Ê±£¬Ò»¸öºÃµÄ¹ýʧ´¦Öóͷ£»úÖƺ͹ýʧҳÏÔµÃÓÈΪÖ÷Òª¡£
±¾ÎĽ«ÏÈÈÝ Laravel ÖеĹýʧ´¦Öóͷ£»úÖÆ£¬ÒÔ¼°ÔõÑù×Ô½ç˵¹ýʧҳÃæºÍÌøת¡£ÎÒÃǽ«ÒÔ Laravel 8 ΪÀý¡£
ÉèÖùýʧ´¦Öóͷ£Æ÷
ÔÚ Laravel ÖУ¬ËùÓеÄÒì³£¶¼»á±»Å׳öµ½Ò»¸öÒì³£´¦Öóͷ£Æ÷ÖС£Õâ¸ö´¦Öóͷ£Æ÷ÈÏÕæÈ·¶¨ÔõÑùÏìÓ¦ÕâЩÒì³£¡£Laravel ĬÈÏÌṩÁËÒ»¸ö AppExceptionsHandler ÀàÀ´´¦Öóͷ£ËùÓÐÒì³£¡£
ÈôÊÇÄúÏë×Ô½ç˵Òì³£ÏìÓ¦£¬¿ÉÒÔÖ±½ÓÔÚ Handler ÀàÖб༡£ºÃ±È£¬Äú¿ÉÒÔͨ¹ý render ÒªÁì×Ô½ç˵Òì³£ÏìÓ¦£º
public function render($request, Throwable $exception) { if ($exception instanceof ModelNotFoundException) { return response()->json([ 'message' => 'Record not found' ], 404); } return parent::render($request, $exception); }
µÇ¼ºó¸´ÖÆ
ÒÔÉÏ´úÂëÑÝʾÁ˵±Ä£×ÓδÕÒµ½Ê±ÔõÑùÏìÓ¦¡£ÕâÀïÎÒÃÇʹÓÃÁË response()->json À´·µ»Ø JSON ÃûÌõĹýʧÏìÓ¦¡£ÈôÊÇÒª·µ»ØÒ»¸öÊÓͼ£¬¿ÉÒÔʹÓà view() ¸¨Öúº¯Êý¡£
×Ô½ç˵ HTTP ¹ýʧҳÃæ
³ýÁËÒì³£´¦Öóͷ£Æ÷£¬ÎÒÃÇ»¹ÐèÒª×Ô½ç˵ HTTP ¹ýʧҳÃæ¡£Laravel ÈÃÕâ¸öÀú³ÌºÜÊǼòÆÓ¡£ÎÒÃÇÖ»ÐèÔÚ resources/views/errors Ŀ¼Ï½¨ÉèÏìÓ¦µÄÊÓͼ¼´¿É¡£ÀýÈ磺
resources/views/errors/404.blade.php ½«´¦Öóͷ£ HTTP 404 ¹ýʧ
resources/views/errors/500.blade.php ½«´¦Öóͷ£ HTTP 500 ¹ýʧ
×¢ÖØ£¬ÄúÈÔÈ»ÐèÒª¶ÔÕâЩÊÓͼ¾ÙÐÐÃÀ»¯ºÍÑùʽµ÷½â¡£ÕâÀïÎÒÃÇÖ»ÌṩÁË×î»ù±¾µÄÏìÓ¦¡£
ÐèҪעÖصÄÊÇ£¬ÈôÊÇÄúµÄÓ¦ÓóÌÐòÔËÐÐÔÚÉú²úģʽÏ£¬²¢ÇÒ»¹Ã»ÓÐÉèÖÃʾÀýÊý¾Ý£¬ÄÇôÄú¿ÉÄÜÐèÒªÐÞ¸Ä APP_DEBUG ÇéÐαäÁ¿ÒÔ½ûÓõ÷ÊÔģʽ£¬²¢È·±£ÆôÓûº´æ¡£
×Ô½ç˵Öض¨Ïò
³ýÁË×Ô½ç˵¹ýʧÏìÓ¦Ö®Í⣬ÎÒÃÇ»¹¿ÉÒÔÔÚÓ¦ÓóÌÐòÖÐ×Ô½ç˵Öض¨Ïò¡£×î³£¼ûµÄÖض¨ÏòÇéÐÎÊǵ±Óû§Î´¾Éí·ÝÑé֤ʱ£¬ÎÒÃÇÐèÒª½«ÆäÖض¨Ïòµ½µÇ¼ҳ¡£ÔÚ Laravel ÖУ¬Ê¹Óà middleware À´±£»¤Â·ÓɺͿØÖÆÆ÷ÒªÁìµÈ¡£
ºÃ±È£¬ÎÒÃÇ¿ÉÒÔʹÓà auth ÖÐÐļþÀ´±£»¤ dashboard ·ÓÉ£º
Route::get('/dashboard', function () { // })->middleware(['auth']);
µÇ¼ºó¸´ÖÆ
µ±Óû§Î´¾Éí·ÝÑé֤ʱ£¬Laravel ½«×Ô¶¯½«Óû§Öض¨Ïòµ½ login ·ÓÉ£¬ÕâÊÇ Laravel ÄÚÖõÄÊÚȨÖÐÐļþµÄ¹¦Ð§¡£ÈôÊÇÄúÏë×Ô½ç˵ÄúµÄÖض¨Ïò£¬Äú¿ÉÒÔʹÓà RedirectIfAuthenticated ÖÐÐļþ£¬ÕâÆäÖÐÐļþ¿ÉÒÔÔÚÓû§ÒѾµÇ¼ʱ½«Óû§Öض¨Ïòµ½Ò»¸öÌض¨µÄÒ³Ãæ¡£
ÀýÈ磬Ҫ½«ÒѵÇÈÎÃü»§´Ó /login Ò³ÃæÖض¨Ïòµ½ /dashboard£º
public function handle($request, Closure $next) { if (Auth::check()) { return redirect('/dashboard'); } return $next($request); }
µÇ¼ºó¸´ÖÆ
Õâ¾ÍÊÇÔõÑùÔÚ Laravel Öд¦Öóͷ£¹ýʧºÍ×Ô½ç˵Öض¨ÏòµÄÒªÁì¡£×Ô½ç˵¹ýʧҳÃæºÍÖض¨ÏòÎÞÒÉ¿ÉÒÔÌá¸ßÓ¦ÓóÌÐòµÄÓû§ÌåÑ飬²¢Ìá¸ßÓ¦ÓóÌÐòµÄ¿É»á¼ûÐÔ¡£ËäÈ»£¬ÕýÈçÎÒÃÇËù˵£¬µ±Óöµ½Î´Öª¹ýʧʱ£¬ÎÒÃÇÒ²Ó¦¸Ã¸ø³öÓѺõĹýʧÌáÐÑ£¬ÒÔ×ÊÖúÓû§È·¶¨ÔõÑù½â¾öÎÊÌâ¡£
ÒÔÉϾÍÊÇlaravel ¹ýʧÌøתµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡