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ÖÐÔõô¾ÙÐйýʧ´¦ÀíµÄÏà¹ØÐÅÏ¢µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡