Custom response during falcon middleware exception

I am writing Falcon middleware for my application. When I get any errors, I want to raise an error, break the process and return my custom answer that looks like this:

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

But the standard Falcon error implementation does not allow me to configure the fields for my answer.

How to solve this problem the most correctly?

+5
source share
2 answers

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

 resp.status = falcon.HTTP_403 resp.body = body return 
+4
source

I was still looking for an example, and here is for those 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 

via:

 error = {"error": [{"message": "Auth token required", "code": "INVALID_HEADER"}]} raise MyHTTPError(falcon.HTTP_400, error) 
+2
source

Source: https://habr.com/ru/post/1261143/


All Articles