From 7d391bb2e24f2940c82bf52e4e5ed5a7643f0c5c Mon Sep 17 00:00:00 2001 From: Fabian Neumann Date: Tue, 24 Jun 2014 21:34:07 +0200 Subject: [PATCH 1/2] New method `RequestHandler.handle_execution_error` --- supercell/requesthandler.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/supercell/requesthandler.py b/supercell/requesthandler.py index a6943d8..d9da6bc 100644 --- a/supercell/requesthandler.py +++ b/supercell/requesthandler.py @@ -116,6 +116,36 @@ def get_template(self, model): ''' raise NotImplemented + def handle_execution_error(self, exception): + '''Handle execution phase exceptions in a customized way. + + Overwrite this method in subclasses to react to certain + exceptions, if the default error handling doesn't fit your + needs. + + For example, to output model validation errors in a custom + JSON representation:: + + def handle_execution_error(self, exception): + from schematics.exceptions import BaseError + if isinstance(exception, BaseError): + self.set_header('Content-Type', 'application/json') + self.set_status(400) + self.write(json.dumps({ + 'error': True, + 'message': exception.messages, + })) + self.finish() + return + raise NotImplementedError + + Note that, if you decide you cannot handle the passed-in + exception, you may ``raise NotImplementedError`` at any time and + the default error handling will take over. + + ''' + raise NotImplementedError + def _execute_method(self): '''Execute the request. From 8b4e5e77b29042e7a7ff400fc9608ccc823f4ef7 Mon Sep 17 00:00:00 2001 From: Fabian Neumann Date: Tue, 24 Jun 2014 21:39:53 +0200 Subject: [PATCH 2/2] Call new `handle_execution_error` before falling back to normal error handling. --- supercell/requesthandler.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/supercell/requesthandler.py b/supercell/requesthandler.py index d9da6bc..574ffcb 100644 --- a/supercell/requesthandler.py +++ b/supercell/requesthandler.py @@ -164,11 +164,15 @@ def _execute_method(self): headers['Content-Type'], self) consumer = consumer_class() kwargs['model'] = consumer.consume(self, model) - except NoConsumerFound: - # TODO return available consumer types?! - raise HTTPError(406) - except StandardError as e: - raise HTTPError(400, reason=unicode(e)) + except (NoConsumerFound, StandardError) as e: + try: + return self.handle_execution_error(e) + except NotImplementedError: + if isinstance(e, NoConsumerFound): + # TODO return available consumer types?! + raise HTTPError(406) + elif isinstance(e, StandardError): + raise HTTPError(400, reason=unicode(e)) if verb in ['get', 'head']: # check if there is caching information stored with the handler