Denys Lytvinyuk
Denys Lytvinyuk

Reputation: 363

Custom response during falcon middleware exception

I'm writing Falcon middleware for my application. When i get any errors i want to raise error, break process and return my custom response, that looks like:

{
   "status": 503,
   "message": "No Token found. Token is required."
}

But standard Falcon error implementation does not allow me to set custom fields to my response.

How to solve this problem most properly?

Upvotes: 7

Views: 2761

Answers (4)

Yves Dorfsman
Yves Dorfsman

Reputation: 3065

raise falcon.HTTPError(falcon.HTTP_503, 'No Token found. Token is required.')

Upvotes: 1

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)

Upvotes: 1

Denys Lytvinyuk
Denys Lytvinyuk

Reputation: 363

After a lot of time spent, I solved this problem in such interesting way. I put my code in a try/catch block, and when an error is caught I decided not to raise Falcon error, and just tried to write return keyword after setting response status and body, because the method is void, so it does not return anything. Now it looks like:

resp.status = falcon.HTTP_403
resp.body = body

return

Upvotes: 7

Vu Viet Hung
Vu Viet Hung

Reputation: 330

I was still looking for an example and here is for anyone who still need it:

from falcon.http_error import HTTPError

class MyHTTPError(HTTPError):

    """Represents a generic HTTP error.
    """

    def __init__(self, status, error):
        super(MyHTTPError, self).__init__(status)
        self.status = status
        self.error = error

    def to_dict(self, obj_type=dict):
        """Returns a basic dictionary representing the error.
        """
        super(MyHTTPError, self).to_dict(obj_type)
        obj = self.error
        return obj

using:

error = {"error": [{"message": "Auth token required", "code": "INVALID_HEADER"}]}

raise MyHTTPError(falcon.HTTP_400, error)

Upvotes: 6

Related Questions