thinkphp5ÖÐÔõô¾ÙÐйýʧ´¦Öóͷ£µÄÏà¹ØÐÅÏ¢
¹ýʧ´¦Öóͷ£»úÖÆ
ThinkPHP5ÌṩÁËÒ»¸öºÜÊÇÍêÕûµÄ¹ýʧ´¦Öóͷ£»úÖÆ£¬ÎÒÃÇ¿ÉÒÔʹÓøûúÖÆÀû±ãµØ´¦Öóͷ£Í¨Àý¹ýʧºÍϵͳ¹ýʧÐÅÏ¢¡£ºÃ±È˵£¬¹ýʧÐÅÏ¢°üÀ¨ÍøÕ¾Ó¦ÓóÌÐòÔÚÔËÐÐʱ·ºÆðµÄ404Ò³ÃæδÕÒµ½¹ýʧ¡¢500ЧÀÍÆ÷ÄÚ²¿¹ýʧºÍ503ЧÀÍÔÝʱ²»¿ÉÓõȡ£HTTP״̬Âë¿ÉÓÃÓÚ±êʶ¹ýʧÐÅÏ¢£¬²¢Æ¾Ö¤Ìض¨µÄÓªÒµÐèÇó¶ÔÆä¾ÙÐÐÏ꾡»¯ÖÎÀí¡£
¸ü½øÒ»²½µØ˵£¬ThinkPHP5ÌṩÁËÒ»¸öÑéÖ¤Â빦Ч£¬¿ÉÒÔ×èÖ¹¶ñÒâ¿Í»§¶Ë¶Ô×ðÁú¿Ê±ÍøÕ¾Ó¦ÓóÌÐò¾ÙÐй¥»÷£¬ÈÃÓ¦ÓóÌÐòÔ½·¢Çå¾²¿É¿¿¡£Ëü»¹Å䱸ÁËÒ»¸öÎó²îÖÎÀí¹¤¾ß£¬ÄÜÀû±ãµØ´¦Öóͷ£ÔÚÑз¢ºÍ²âÊÔÖз¢Ã÷µÄ¹ýʧÐÅÏ¢¡£
½¨Éè¹ýʧҳÃæ
Á¬Ã¦Ñ§Ï°¡°PHPÃâ·ÑѧϰÌõ¼Ç£¨ÉîÈ룩¡±£»
ÎÒÃÇ¿ÉÒÔʹÓÃ×Ô½ç˵¹ýʧҳÃæÀ´·ºÆðÔ½·¢ÓѺõĹýʧÐÅÏ¢£¬ÔÚThinkPHP5¿ò¼ÜÖС£ÎÒÃÇÖ»ÐèÒªÔÚ×Ô½ç˵µÄ¹ýʧҳÃæÖÐÌí¼ÓÐëÒªµÄ´¦Öóͷ£´úÂë¼´¿É¡£ÏÂÃæÊÇÔõÑù½¨Éè×Ô½ç˵¹ýʧҳÃæµÄ°ì·¨£º
ÔÚ×ðÁú¿Ê±Ó¦ÓóÌÐòµÄ¸ùĿ¼Öн¨ÉèÒ»¸öÃüÃûΪ¡°exception¡±µÄÎļþ¼Ð£»
ÔÚÕâ¸öÎļþ¼ÐÖн¨ÉèÒ»¸öÀàÃüÃûΪ¡°Handle¡±£»
´¦Öóͷ£¹ýʧÐÅÏ¢ºÍÒì³£ÐÅÏ¢´úÂë¡£
µÚÒ»²½ºÍµÚ¶þ²½ÒѾÍê³ÉÁË£¬ÏÂÃæÎÒÃÇÀ´µ½Á˵ÚÈý²½£¬´¦Öóͷ£¹ýʧÐÅÏ¢ºÍÒì³£ÐÅÏ¢¡£
´¦Öóͷ£¹ýʧÐÅÏ¢ºÍÒì³£ÐÅÏ¢
ÔÚThinkPHP5¿ò¼ÜÖУ¬ÎÒÃÇ¿ÉÒÔʹÓûùÀà¡°think\exception\Handle¡±Öеġ°render¡±ÒªÁì´¦Öóͷ£Òì³£ÐÅÏ¢¡£¿ÉÒÔʹÓøÃÒªÁì·µ»ØÒ»¸ö¹ýʧҳÃ棬ÀýÈ磺
use think\exception\HttpException; use think\exception\ValidateException; use think\Response; class Handle extends think\exception\Handle { public function render(Exception $e): Response { if ($e instanceof HttpException && $this->isAjax()) { $data = [ 'msg' => $e->getMessage(), 'code' => $e->getStatusCode(), ]; return json($data, $e->getStatusCode()); } if ($e instanceof ValidateException) { return json($e->getError(), 422); } // ÆäËû¹ýʧ½»¸øϵͳ´¦Öóͷ£ return parent::render($e); } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊö´úÂëÖУ¬ÎÒÃǽç˵ÁËÒ»¸öÃûΪ¡°render¡±µÄÒªÁ죬Æä×÷ÓÃÊÇƾ֤ת´ïµÄÒì³£ÐÅÏ¢²ÎÊýÀ´´¦Öóͷ£ÕâЩÒì³£ÐÅÏ¢¡£·µ»Ø JSON ÏìÓ¦µÄÌõ¼þÊÇת´ïµÄÒì³£ÊôÓÚ HttpException ºÍÑéÖ¤Òì³£¡£ÈôÊDz»ÊÇ£¬Ôò½«Ò쳣ת´ï¸øÇ°¶ËÏìÓ¦£¬²¢Ê¹Óø¸ÀàĬÈÏ·µ»ØÒ³Ãæ¡£
ÎÒÃÇÌṩÁËÒ»ÖÖ¼òÆÓµÄÒªÁ죬ÈÃÄú¿ÉÒÔ¿ìËÙ½¨ÉèºÍ´¦Öóͷ£×Ô½ç˵¹ýʧҳÃæ¡£ÕâÕýÊÇΪʲôÎÒÃÇÒÔΪThinkPHP5ÊÇÒ»¸ö×îºÃµÄPHP¿ò¼ÜÖ®Ò»£¬²¢ÇÒΪ³ÌÐòÔ±ÌṩÁËÇ¿Ê¢¶øÇáËɵĿª·¢¹¤¾ß¡£
ÒÔÉϾÍÊÇthinkphp5ÖÐÔõô¾ÙÐйýʧ´¦Öóͷ£µÄÏà¹ØÐÅÏ¢µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡