Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

handle errors in flask

from flask import Flask, abort
from auth import AuthError
# depending on the error either 400 or any
#just work with the following

@app.errorhandler(404)
def resource_not_found(error):
  return jsonify({
    "success":  True,
    "error": 404,
    "message": "Resource not found"
  }), 404
##This works for any type of status code error
#You'll follow the same steps just change the error value and message :)

### also for Auth error. 

@app.errorhandler(AuthError)
def AuthError(error):
  """Need to return JSON and we'll have to get a response""" 
  response = jsonify(error)
  response.status_code = error.status_code
  
  return response
Comment

flask error handling

from flask import json
from werkzeug.exceptions import HTTPException

@app.errorhandler(HTTPException)
def handle_exception(e):
    """Return JSON instead of HTML for HTTP errors."""
    # start with the correct headers and status code from the error
    response = e.get_response()
    # replace the body with JSON
    response.data = json.dumps({
        "code": e.code,
        "name": e.name,
        "description": e.description,
    })
    response.content_type = "application/json"
    return response
Comment

flask error handling

from werkzeug.exceptions import HTTPException

@app.errorhandler(Exception)
def handle_exception(e):
    # pass through HTTP errors
    if isinstance(e, HTTPException):
        return e

    # now you're handling non-HTTP exceptions only
    return render_template("500_generic.html", e=e), 500
Comment

PREVIOUS NEXT
Code Example
Python :: flask autherror 
Python :: time py 
Python :: roman to integer python 
Python :: django reverse queryset 
Python :: pandas describe kurtosis skewness 
Python :: how to use enumerate in python 
Python :: Sorting Dataframes by Column Python Pandas 
Python :: plt.annotate text size 
Python :: find max length in string in pandas dataframe 
Python :: plot background color matplotlib 
Python :: drupal 8 request_time 
Python :: numpy as array 
Python :: how to display percentage in pandas crosstab 
Python :: numpy is not nan 
Python :: numpy array length 
Python :: Double-Linked List Python 
Python :: django boilerplate command 
Python :: python list divide 
Python :: pandas bin columns 
Python :: jupyter notebook for pdf generation 
Python :: km/h to mph python 
Python :: python fillna with mean in a dataframe 
Python :: html.unescape python 
Python :: System.Windows.Forms.DataGridView.CurrentRow.get returned null. c# 
Python :: read emails from gmail python 
Python :: python input timeout 
Python :: python convert date to timestamp 
Python :: python recursively print directory 
Python :: dimension of tensor 
Python :: change value in excel using python 
ADD CONTENT
Topic
Content
Source link
Name
5+9 =