herlambang
herlambang

Reputation: 185

Flask JSON Custom Error Page

is there any implementation exists on JSON as custom error page on Flask?

Upvotes: 7

Views: 6168

Answers (1)

rootsmith
rootsmith

Reputation: 856

You can create a json response object using the "jsonify" helper from flask and then set the status_code of the response before returning it like this:

def not_found(error):
    response = jsonify({'code': 404,'message': 'No interface defined for URL'})
    response.status_code = 404
    return response

You can register this function as the handler by wrapping it in the errorhandler:

@app.errorhandler(404)
def not_found(error):
    ...

OR, setting it directly on the error_handler_spec:

app.error_handler_spec[None][404] = not_found

Upvotes: 30

Related Questions