0

I'm using Turbogears2 to develop a small web application. And in some of my "controllers", I would like to response the client a json object with error information inside instead of an html page follows the standard error page template, because the ajax client can read the error message and have it's own way to display it.

Mingcai SHEN
  • 117
  • 1
  • 8

1 Answers1

1

There are multiple ways you can achieve this. If it is only bound to some controller you can easily register a controller wrapper for them (using tg.hooks.wrap_controller) and return JSON instead of plain error when needed. Controller wrappers are documented on http://turbogears.readthedocs.org/en/latest/turbogears/hooks.html#controller-wrappers

Otherwise another options is to use a decorator on the controller function to catch the error. This is what is also done by tgext.crudwhen reporting json errors through the catch_errors custom decorator: https://github.com/TurboGears/tgext.crud/blob/master/tgext/crud/decorators.py#L114

The controller wrapper solution is usually more powerful as it can be applied also to third party controllers. Otherwise you can even hijack the ErrorController in controllers/error.py to return json using json.dumps (TurboGears returns the response as is when it's a string or a tg.Response instance).

amol
  • 1,771
  • 1
  • 11
  • 15