Skip to content

Instantly share code, notes, and snippets.

@markph0204
Last active December 14, 2017 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markph0204/26bdf4b6f0c03b1bf43e8e78c2a243dc to your computer and use it in GitHub Desktop.
Save markph0204/26bdf4b6f0c03b1bf43e8e78c2a243dc to your computer and use it in GitHub Desktop.
Handling invalid requests with Flask - Implementing API Exceptions
# 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