Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python flask and custom client error messages

I'm currently writing a REST API for an app I'm working on. The app is written in python using flask. I have the following:

try:
    _profile = profile(
        name=request.json['name'],
        password=profile.get_salted_password('blablabla'),
        email=request.json['email'],
        created_by=1,
        last_updated_by=1
    )
except AssertionError:
    abort(400)

session = DatabaseEngine.getSession()
session.add(_profile)
try:
    session.commit()
except IntegrityError:
    abort(400)

The error handler looks like this:

@app.errorhandler(400)
def not_found(error):
    return make_response(standard_response(None, 400, 'Bad request'), 400)

I'm using the error 400 to denote both a problem with a sqlalchemy model validator and a unique constraint when writing to the database and in both cases the following error is sent to the client:

{
  "data": null,
  "error": {
    "msg": "Bad request",
    "no": 400
  },
  "success": false
}

Is there a way to still use abort(400) but also set the error somehow so that the error handler can take care of adding additional information for the error object in the result?

I would like it to be more in line with:

{
  "data": null,
  "error": {
    "msg": "(IntegrityError) duplicate key value violates unique constraint profile_email_key",
    "no": 400
  },
  "success": false
}
like image 466
Asken Avatar asked Aug 06 '13 13:08

Asken


People also ask

How do I create a custom error page in flask?

Flask comes with a handy abort() function that aborts a request with an HTTP error code early. It will also provide a plain black and white error page for you with a basic description, but nothing fancy. Depending on the error code it is less or more likely for the user to actually see such an error.

Which is client error in flask?

When an error occurs in Flask, an appropriate HTTP status code will be returned. 400-499 indicate errors with the client's request data, or about the data requested. 500-599 indicate errors with the server or application itself. You might want to show custom error pages to the user when an error occurs.

How does python handle 404 error flask?

For this, we need to download and import flask. Download the flask through the following commands on CMD. Using app.py as our Python file to manage templates, 404. html be the file we will return in the case of a 404 error and header.


1 Answers

you can directly put a custom response in abort() function:

abort(make_response("Integrity Error", 400))

Alternatively, you can put it in the error handler function

@app.errorhandler(400)
def not_found(error):
resp = make_response("Integrity Error", 400)
return resp
like image 58
codegeek Avatar answered Oct 19 '22 02:10

codegeek