From b81f39aee596c660efc9fbbf87d2247aee485d95 Mon Sep 17 00:00:00 2001 From: Ingo Schommer Date: Fri, 8 Mar 2013 12:50:27 +0100 Subject: [PATCH] API Handle uncaught ValidationException on CMS controller execution This removes the need for a lot of boilerplate code around DataObject->write() logic, and avoids generic 500 errors on user-level failures. This should really be a per-project choice, but at the moment request handling doesn't allow to configure custom exception handling. --- admin/code/LeftAndMain.php | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/admin/code/LeftAndMain.php b/admin/code/LeftAndMain.php index 85921a141..ac148af5e 100644 --- a/admin/code/LeftAndMain.php +++ b/admin/code/LeftAndMain.php @@ -354,7 +354,18 @@ class LeftAndMain extends Controller implements PermissionProvider { } public function handleRequest(SS_HTTPRequest $request, DataModel $model = null) { - $response = parent::handleRequest($request, $model); + try { + $response = parent::handleRequest($request, $model); + } catch(ValidationException $e) { + // Nicer presentation of model-level validation errors + $msgs = _t('LeftAndMain.ValidationError', 'Validation error') . ': ' + . $e->getResult()->message(); + $e = new SS_HTTPResponse_Exception($msgs, 403); + $e->getResponse()->addHeader('Content-Type', 'text/plain'); + $e->getResponse()->addHeader('X-Status', rawurlencode($msgs)); + throw $e; + } + $title = $this->Title(); if(!$response->getHeader('X-Controller')) $response->addHeader('X-Controller', $this->class); if(!$response->getHeader('X-Title')) $response->addHeader('X-Title', $title);