Bird
Raised Fist0
Flaskframework~10 mins

API error handling in Flask - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - API error handling
Client sends request
↓
API receives request
↓
Process request
↓
Error occurs?
No→Return success response
Yes↓
Catch error
↓
Return error response with status code
↓
Client receives error info
The API receives a request, processes it, and if an error happens, it catches it and sends back an error response with a status code.
Execution Sample
Flask
from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/divide/<int:a>/<int:b>')
def divide(a, b):
    try:
        result = a / b
        return jsonify({'result': result})
    except ZeroDivisionError:
        return jsonify({'error': 'Cannot divide by zero'}), 400
This API endpoint divides two numbers and returns the result or an error if dividing by zero.
Execution Table
StepInput (a,b)ActionResultResponse Sent
1a=10, b=2Try division10 / 2 = 5.0{'result': 5.0}, status 200
2a=5, b=0Try divisionZeroDivisionError raised{'error': 'Cannot divide by zero'}, status 400
3a=7, b=1Try division7 / 1 = 7.0{'result': 7.0}, status 200
4a=3, b=0Try divisionZeroDivisionError raised{'error': 'Cannot divide by zero'}, status 400
5-No more requests--
💡 Execution stops after all requests are processed.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
a-10573-
b-2010-
result-5.0Error7.0Error-
response-{'result': 5.0}, 200{'error': 'Cannot divide by zero'}, 400{'result': 7.0}, 200{'error': 'Cannot divide by zero'}, 400-
Key Moments - 2 Insights
Why does the API return a 400 status code when dividing by zero?
Because the ZeroDivisionError is caught and the API sends a JSON error message with status 400, as shown in execution_table rows 2 and 4.
What happens if no error occurs during division?
The API returns the division result in JSON with status 200, as seen in execution_table rows 1 and 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the response when a=5 and b=0?
A{'result': 1.0}, status 200
B{'result': 5.0}, status 200
C{'error': 'Cannot divide by zero'}, status 400
DNo response
💡 Hint
Check row 2 in the execution_table where b=0 causes an error response.
At which step does the division succeed without error?
AStep 2
BStep 1
CStep 4
DStep 5
💡 Hint
Look for steps where 'result' is a number, not 'Error' in variable_tracker.
If we remove the try-except block, what would happen when b=0?
AAPI crashes and returns a server error (500)
BAPI returns a JSON error with status 400
CAPI returns result 0
DAPI returns status 200 with empty response
💡 Hint
Without catching ZeroDivisionError, Python raises an exception causing a server error.
Concept Snapshot
API error handling in Flask:
- Use try-except inside route functions
- Catch specific errors (e.g., ZeroDivisionError)
- Return JSON error message with HTTP status code
- Normal responses return data with status 200
- Helps client understand what went wrong
Full Transcript
This example shows how a Flask API handles errors by using try-except blocks inside route functions. When dividing two numbers, if the divisor is zero, a ZeroDivisionError occurs. The API catches this error and returns a JSON response with an error message and status code 400. If no error occurs, it returns the division result with status 200. This approach helps clients know if their request failed and why, improving communication and reliability.

Practice

(1/5)
1. What is the main purpose of using @app.errorhandler in a Flask API?
easy
A. To start the Flask application
B. To define new API routes
C. To catch specific errors and return custom responses
D. To connect to a database

Solution

  1. Step 1: Understand the role of @app.errorhandler

    This decorator is used to catch errors that happen during API requests.
  2. Step 2: Recognize its use for custom responses

    It allows you to send back clear messages and proper HTTP status codes when errors occur.
  3. Final Answer:

    To catch specific errors and return custom responses -> Option C
  4. Quick Check:

    @app.errorhandler catches errors [OK]
Hint: Remember: errorhandler catches errors to customize responses [OK]
Common Mistakes:
  • Thinking it defines routes
  • Confusing it with app.run()
  • Assuming it manages database connections
2. Which of the following is the correct syntax to handle a 404 error in Flask?
easy
A. @app.errorhandler(404) def not_found(error): return 'Not Found', 404
B. @app.route(404) def not_found(): return 'Not Found'
C. @app.errorhandler('404') def not_found(error): return 'Not Found', 404
D. @app.errorhandler(404) def not_found(): return 'Not Found'

Solution

  1. Step 1: Identify correct decorator usage

    The @app.errorhandler decorator takes an integer status code like 404 without quotes.
  2. Step 2: Check function signature and return

    The handler function should accept an error argument and return a response with the status code.
  3. Final Answer:

    @app.errorhandler(404)\ndef not_found(error):\n return 'Not Found', 404 -> Option A
  4. Quick Check:

    Correct decorator and function signature = @app.errorhandler(404) def not_found(error): return 'Not Found', 404 [OK]
Hint: Use integer status codes without quotes in errorhandler [OK]
Common Mistakes:
  • Using @app.route instead of @app.errorhandler
  • Passing status code as string '404'
  • Omitting the error parameter in handler function
3. Given this Flask error handler code:
from flask import abort, jsonify
@app.errorhandler(400)
def bad_request(error):
    return jsonify({'error': 'Bad Request'}), 400

@app.route('/test')
def test():
    abort(400)

What will be the JSON response and status code when accessing /test?
medium
A. {"error": "Bad Request"} with status code 400
B. Plain text 'Bad Request' with status code 200
C. Default Flask 400 error page with status code 400
D. Empty response with status code 400

Solution

  1. Step 1: Understand abort triggers error handler

    The abort(400) call triggers the 400 error handler defined by @app.errorhandler(400).
  2. Step 2: Check handler return value

    The handler returns a JSON dictionary with the error message and status code 400.
  3. Final Answer:

    {"error": "Bad Request"} with status code 400 -> Option A
  4. Quick Check:

    abort triggers handler response JSON + 400 [OK]
Hint: abort(code) triggers matching errorhandler response [OK]
Common Mistakes:
  • Expecting plain text instead of JSON
  • Assuming default Flask error page shows
  • Missing status code in response
4. What is wrong with this Flask error handler code?
@app.errorhandler(500)
def internal_error():
    return {'error': 'Server Error'}, 500
medium
A. The decorator should be @app.route, not @app.errorhandler
B. The status code 500 should be a string '500'
C. The return value must be a string, not a dictionary
D. The handler function must accept an error parameter

Solution

  1. Step 1: Check function signature for error handlers

    Error handler functions must accept one parameter for the error object.
  2. Step 2: Identify missing parameter

    The function internal_error has no parameters, so Flask will raise a TypeError.
  3. Final Answer:

    The handler function must accept an error parameter -> Option D
  4. Quick Check:

    Error handler functions need error argument [OK]
Hint: Error handlers always need an error parameter [OK]
Common Mistakes:
  • Omitting the error parameter
  • Using string status codes
  • Confusing errorhandler with route decorator
5. You want to create a Flask API error handler that returns a JSON response with a custom message and the correct HTTP status code for any KeyError raised in your routes. Which of the following is the best way to implement this?
hard
A. @app.errorhandler(400) def handle_key_error(error): return {'error': 'Missing key in request'}, 400
B. @app.errorhandler(KeyError) def handle_key_error(error): return {'error': 'Missing key in request'}, 400
C. @app.route('/error') def handle_key_error(): return {'error': 'Missing key in request'}, 400
D. @app.errorhandler(Exception) def handle_key_error(error): return {'error': 'Missing key in request'}, 400

Solution

  1. Step 1: Use exception class in errorhandler

    To catch a specific Python error like KeyError, use it directly in @app.errorhandler(KeyError).
  2. Step 2: Return JSON with appropriate status code

    Return a JSON message and HTTP 400 (bad request) status code to indicate client error.
  3. Final Answer:

    @app.errorhandler(KeyError)\ndef handle_key_error(error):\n return {'error': 'Missing key in request'}, 400 -> Option B
  4. Quick Check:

    Use exception class in errorhandler for specific errors [OK]
Hint: Use exception class in errorhandler to catch specific errors [OK]
Common Mistakes:
  • Using status code instead of exception class
  • Defining error handler as a route
  • Catching all exceptions instead of specific one
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard