Search code examples
pythonflaskflask-restful

Error handler is not invoked in production


When I use Flask dev server and Exception is raised I get proper error code and my custom error message. But that doesn't work in production environment (I use lighttpd with fcgi), I just get 500 error there.

Here's how my exception looks like:

class InvalidSettings(Exception):
    status_code = 400

    def __init__(self, message, status_code=None, payload=None):
        super(InvalidSettings, self).__init__()
        self.message = message
        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

    def to_dict(self):
        rv = dict(self.payload or ())
        rv['message'] = self.message
        return rv

And here's the error handler code:

@app.errorhandler(InvalidSettings)
def handle_invalid_settings(error):
    response = json.dumps(error.to_dict())
    response.status_code = error.status_code
    return response

UPDATE

I tried to use custom error messages but I get exception:

TypeError: __init__() got an unexpected keyword argument 'errors'

And that's true, there's no such thing in Api constructor in Flask-RESTful. That's weird because it's documentation for version 0.2.1 and as I can see in pip my version is 0.2.12. Hovewer, I can't figure out if it is what I actually need.


Solution

  • I installed latest version from master branch and there's errors argument for Api constructor.

    Now it returns proper exceptions after I changed code a little bit, as documentation suggests:

    errors = {
        'InvalidSettings': {
            'message': "Something is wrong with your settings",
            'status': 400,
        }
    }
    api = restful.Api(app, errors=errors)
    

    But there's still a question, maybe I missed something in documentation. How can I pass the message from the place where I raise it?