Custom response during falcon middleware exception
Asked Answered
T

4

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?

Toname answered 12/12, 2016 at 14:28 Comment(0)
T
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
Toname answered 12/12, 2016 at 15:24 Comment(0)
M
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)
Mafia answered 15/8, 2017 at 1:37 Comment(0)
L
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)
Locular answered 11/4, 2018 at 4:56 Comment(0)
S
1
raise falcon.HTTPError(falcon.HTTP_503, 'No Token found. Token is required.')
Shopper answered 22/4, 2018 at 0:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.