Last active
December 14, 2017 11:31
-
-
Save markph0204/26bdf4b6f0c03b1bf43e8e78c2a243dc to your computer and use it in GitHub Desktop.
Handling invalid requests with Flask - Implementing API Exceptions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# http://flask.pocoo.org/docs/0.12/patterns/apierrors/ | |
from flask import jsonify | |
class InvalidUsage(Exception): | |
status_code = 400 | |
def __init__(self, message, status_code=None, payload=None): | |
Exception.__init__(self) | |
self.message = message | |
if status_code is not None: | |
self.status_code = status_code | |
self.payload = payload | |
def to_dict(self): | |
rv = dict(self.payload or ()) | |
rv['message'] = self.message | |
return rv | |
@app.errorhandler(InvalidUsage) | |
def handle_invalid_usage(error): | |
response = jsonify(error.to_dict()) | |
response.status_code = error.status_code | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment