1

I want to add my own http status code to my Flask application. Here is my code:

from werkzeug import exceptions

class UnrecognizedParametersOrCombination(exceptions.HTTPException):
    code = 460
    description = 'The query parameters or their combination are not recognized!'


exceptions.default_exceptions[460] = UnrecognizedParametersOrCombination

But when I call abort(460), I got error: LookupError: no exception for 460

It seems I didn't correctly register the new exception to werkzeug default exceptions. The official document is quite blur on this part. How should I do this?

3 Answers 3

1

You shouldn't be doing this, as you would break the RFCs associated with the HTTP status codes. HTTP status codes are supposed to be universal and not misused. I'd recommend responding some JSON, like "status": "460", if you want to use your own debugging codes, just don't use them as HTTP responses.

Sign up to request clarification or add additional context in comments.

1 Comment

Why can't you have different RFC error codes? Not all of them are used. (I.e. 460 has no meaning that is still relevant: rfc-editor.org/info/rfc460)
1

OK, I figured it out. According to the document: http://flask.pocoo.org/docs/1.0/errorhandling/ This is not doable. What we can do is to define an exception, and raise() it instead of abort() it. It seems now werkzeug doesn't support registering a customized http status code in its default exceptions any longer...

So now my working code is:

from werkzeug import exceptions

class UnrecognizedParametersOrCombination(exceptions.HTTPException):
    code = 460
    description = 'The query parameters or their combination are not recognized!'


def handle_460(e):
    return render_template('460.html')


app.register_error_handler(UnrecognizedParametersOrCombination, handle_460)

And now I need to use raise UnrecognizedParametersOrCombination() instead of abort(460) for responding. And so, the response is a 200 instead of a non-officially-supported 460.

Comments

0

Tried abort mapping?

abort.mappings[460] = UnrecognizedParametersOrCombination

1 Comment

Seems this api is not available any longer since 0.11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.