diff --git a/supercell/requesthandler.py b/supercell/requesthandler.py index a6943d8..574ffcb 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. @@ -134,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