Like many others, I've struggled with getting Pyramid to render JSON exceptions. Thanks to a few recent updates to Pyramid and WebOb, things got a whole lot easier.
The new behavior allows for JSON to be generated based on the "accept" request headers. Unfortunately, sending this header might not be possible (or easy) with low-level clients and utilities. While testing some approaches, I came across the following trick:
@view_config(context=HTTPException)
def exception_view__upgrade(exc, request):
"""if we end with .json, serve json."""
if (request.path[-5:]).lower() == '.json':
request.environ['HTTP_ACCEPT'] = "application/json"
return exc
I just used the `request.path` to ensure the test in `pyramid/httpexceptions.py` passes if a ".json" document is requested. Depending on your needs, you may want to use another condition. If you're already using a custom `context=HTTPException` view, this would need to be factored in. This behavior works because of a few current implementation details on Pyramid, so it's not guaranteed to last... but for now it works and has saved me a lot of grief.
(i accidentally posted a version of this earlier with some code for customizing exceptions that wasn't properly abstracted out and didn't work outside my application. sorry if you saw that.)