Consider this Python Flask code snippet that handles errors:
from flask import Flask, jsonify
app = Flask(__name__)
@app.errorhandler(500)
def internal_error(error):
return jsonify({'error': 'Internal Server Error'}), 500
@app.route('/cause_error')
def cause_error():
1 / 0 # This will cause a ZeroDivisionError
if __name__ == '__main__':
app.run()What will the client receive when accessing /cause_error?
from flask import Flask, jsonify app = Flask(__name__) @app.errorhandler(500) def internal_error(error): return jsonify({'error': 'Internal Server Error'}), 500 @app.route('/cause_error') def cause_error(): 1 / 0 # This will cause a ZeroDivisionError if __name__ == '__main__': app.run()
Think about what the @app.errorhandler(500) decorator does.
The @app.errorhandler(500) decorator catches unhandled exceptions like ZeroDivisionError and returns the JSON response with status 500. So the client receives the JSON error message with HTTP 500.
Which of the following best explains the cause of a 500 Internal Server Error in a REST API?
Think about whether the problem is on the client or server side.
A 500 Internal Server Error means the server failed due to an unexpected problem while processing a valid request. It is a server-side error, not caused by the client.
Look at this Node.js Express code snippet:
const express = require('express');
const app = express();
app.get('/data', (req, res) => {
const data = JSON.parse('{invalid json}');
res.json(data);
});
app.listen(3000);What will happen when a client requests /data?
Consider what happens when JSON.parse receives invalid JSON.
JSON.parse throws a SyntaxError on invalid JSON. Since the error is not caught, Express returns a 500 Internal Server Error response.
Choose the correct Express.js code to send a 500 Internal Server Error with a JSON message {"error": "Server failure"}:
Check the Express.js method chaining syntax for setting status and sending JSON.
In Express, res.status(500).json(...) sets the HTTP status code and sends a JSON response. Other options use invalid or deprecated syntax.
You are designing a REST API. Which approach best prevents unhandled exceptions causing 500 Internal Server Errors?
Think about how to handle errors gracefully on the server side.
Wrapping code in try-catch blocks allows catching errors and returning controlled responses, preventing unexpected 500 errors and improving API reliability.