Creative crypter
Creative crypter

Reputation: 1516

How to raise exceptions as json?

At the service level of my application, I am raising an exception and I want it to be printed as JSON to the browser.

I implemented it as stated in the documentation:

raise falcon.HTTPError(
    '12345 - My Custom Error',
    'some text'
).to_json()

And the output from the console:

TypeError: exceptions must derive from BaseException

Anybody had this issue before and could help me with this one?

Upvotes: 3

Views: 11113

Answers (2)

aleem md
aleem md

Reputation: 72

Create custom exception class explained in falcon docs, search for add_error_handler

class RaiseUnauthorizedException(Exception):
    def handle(ex, req, resp, params):
        resp.status = falcon.HTTP_401
        response = json.loads(json.dumps(ast.literal_eval(str(ex))))
        resp.body = json.dumps(response)

Add custom exception class to falcon API object

api = falcon.API()
api.add_error_handler(RaiseUnauthorizedException)

import Custom exception class and pass your message

message = {"status": "error", "message" : "Not authorized"}
RaiseUnauthorizedException(message)

Upvotes: 0

kichik
kichik

Reputation: 34744

You're trying to raise a string. The correct way to do that is with set_error_serializer().

The example from the documentation seems like exactly what you need (plus YAML support).

def my_serializer(req, resp, exception):
    representation = None

    preferred = req.client_prefers(('application/x-yaml',
                                    'application/json'))

    if preferred is not None:
        if preferred == 'application/json':
            representation = exception.to_json()
        else:
            representation = yaml.dump(exception.to_dict(),
                                       encoding=None)
        resp.body = representation
        resp.content_type = preferred

    resp.append_header('Vary', 'Accept')

app = falcon.API()
app.set_error_serializer(my_serializer)

Upvotes: 3

Related Questions