Flask-restful: Use message from exception in custom error messages

Created on 23 Jul 2014  路  5Comments  路  Source: flask-restful/flask-restful

In docs I see that I'm able to specify just one message per exception using that dictionary.

But what if I need to pass more informative message? For example, If there are some validation errors, I'd like to know what value is actually wrong.

enhancement

Most helpful comment

@jgehrcke, this implements exactly your syntax. Works well for me. Hope it gets integrated into Flask RESTful soon.

All 5 comments

I think you are looking for #221.

@shuaishuai I've already seen that thing. Maybe I missed something, but there can be only one message for exception in this case. In my case, I pass a message as a payload when I raise the exception, so I can tell user what's wrong with settings that he tries to set. It seems a lot better to me to use flask error handlers with flask-RESTful, but, as I can see, they simply don't work in this case.

Indeed, I used FR for the first time today and found it great -- up to the point where I needed to implement some custom error handling. Honestly, the entire idea of this error dictionary described in
http://flask-restful.readthedocs.org/en/latest/extending.html#custom-error-handlers is plain inconvenient -- why should we hard-code error messages at application startup? No way to include any kind of context-specific detail into these error messages later on. The whole point of a good error message is that it is created _dynamically_, adjusted to the actual error, created _after_ the error is known exactly. I want to be able to handle exceptions in requests processed by FR in the _same_ way as vanilla flask can handle exceptions.

That is, given such a FR resource (snippet):

class Entity(Resource):

    def post(self):
        raise CustomException(msg="Doh!", code=1337)

I want to be able to handle this exception freely, in this fashion:

@api.errorhandler(CustomException)
def handle_invalid_request(e):
    return e.response()

Then I can build the response in the response() method of the CustomException type without any limitations.

How do I achieve this or something with comparably few limitations?

I agree with @jgehrcke that a more dynamic way of handling errors would be useful. And if it uses a technique similar to core Flask like @api.errorhandler that would be preferable.

@jgehrcke, this implements exactly your syntax. Works well for me. Hope it gets integrated into Flask RESTful soon.

Was this page helpful?
0 / 5 - 0 ratings