Custom Interrupt / Exception Display in Flask

The default message for Flask 400( abort()) exception is :

{
  "message": "The browser (or proxy) sent a request that this server could not understand."
}

For 404:

{
  "message": "The requested URL was not found on the server.  If you entered the URL manually please check your spelling and try again. You have requested this URI [/obj/] but did you mean /obj/ or /obj/<int:id>/ or /obj/<int:id>/kill/ ?"
}

I am having trouble understanding these messages when I receive them as responses in my API (especially the first one, I thought something was wrong with the encryption or headers) and it seems to me tiring to try to redefine the text manually for each exception abort(). Therefore, I change the display:

from flask import abort
from werkzeug.exceptions import HTTPException


class BadRequest(HTTPException):
    code = 400
    description = 'Bad request.'


class NotFound(HTTPException):
    code = 404
    description = 'Resource not found.'


abort.mapping.update({
    400: BadRequest,
    404: NotFound
})

400 . 404, . - abort(400), abort(403) , abort(404). . ?

. , abort, flask not flask_restful, , , Aborter. , , , , .

2. abort.mapping . , , , 404. Proofpic

3. , . ( , ).

+4
2

, , 404. . . , , , . ERROR_404_HELP = False , .

, ? , , , . googled , GitHub (1, 2).

, .

+4

... , , ( !), , . , , , , , , , , .

from flask import abort

abort(404, "And here why.")
+1

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


All Articles