7

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?

Denys Lytvinyuk
  • 353
  • 4
  • 13

4 Answers4

6

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
SiHa
  • 7,830
  • 13
  • 34
  • 43
Denys Lytvinyuk
  • 353
  • 4
  • 13
5

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)
Vu Viet Hung
  • 180
  • 3
  • 7
1

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)
aleem md
  • 72
  • 1
  • 4
1
raise falcon.HTTPError(falcon.HTTP_503, 'No Token found. Token is required.')
Yves Dorfsman
  • 2,684
  • 3
  • 20
  • 28