From d041ee665cb101b19eb3a89ccf941a56a1642c98 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 4 Jun 2016 17:52:47 +0800 Subject: [PATCH] =?UTF-8?q?Controller=E5=92=8CModel=E7=B1=BB=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0failException=E6=96=B9=E6=B3=95=20=E7=94=A8=E4=BA=8E?= =?UTF-8?q?=E8=AE=BE=E7=BD=AE=E9=AA=8C=E8=AF=81=E5=A4=B1=E8=B4=A5=E5=90=8E?= =?UTF-8?q?=E6=98=AF=E5=90=A6=E6=8A=9B=E5=87=BA=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Controller.php | 21 ++++++++++++++++++++- library/think/Model.php | 21 ++++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/library/think/Controller.php b/library/think/Controller.php index 5920d7c0..0fc04c49 100644 --- a/library/think/Controller.php +++ b/library/think/Controller.php @@ -13,6 +13,7 @@ namespace think; \think\Loader::import('controller/Jump', TRAIT_PATH, EXT); +use think\Exception; use think\Request; use think\View; @@ -24,6 +25,8 @@ class Controller protected $view = null; // Request实例 protected $request; + // 验证失败是否抛出异常 + protected $failException = false; /** * 前置操作方法列表 @@ -136,6 +139,18 @@ class Controller $this->view->engine($engine); } + /** + * 设置验证失败后是否抛出异常 + * @access public + * @param bool $fail 是否抛出异常 + * @return $this + */ + public function failException($fail = true) + { + $this->failException = $fail; + return $this; + } + /** * 验证数据 * @access public @@ -170,7 +185,11 @@ class Controller } if (!$v->check($data)) { - return $v->getError(); + if ($this->failException) { + throw new Exception($v->getError()); + } else { + return $v->getError(); + } } else { return true; } diff --git a/library/think/Model.php b/library/think/Model.php index 86c33325..3bd42ca1 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -14,6 +14,7 @@ namespace think; use think\Cache; use think\Db; use think\db\Query; +use think\Exception; use think\Loader; use think\model\Relation; use think\paginator\Collection as PaginatorCollection; @@ -85,6 +86,8 @@ abstract class Model implements \JsonSerializable, \ArrayAccess protected $relation; // 属性类型 protected $fieldType = []; + // 验证失败是否抛出异常 + protected $failException = false; /** * 初始化过的模型. @@ -703,6 +706,18 @@ abstract class Model implements \JsonSerializable, \ArrayAccess return $this; } + /** + * 设置验证失败后是否抛出异常 + * @access public + * @param bool $fail 是否抛出异常 + * @return $this + */ + public function failException($fail = true) + { + $this->failException = $fail; + return $this; + } + /** * 自动验证数据 * @access protected @@ -729,7 +744,11 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } if (!$validate->check($data)) { $this->error = $validate->getError(); - return false; + if ($this->failException) { + throw new Exception($this->error); + } else { + return false; + } } $this->validate = null; }