- Python Microservices Development
- Tarek Ziadé
- 420字
- 2021-07-02 18:54:23
Custom error handler
When your code does not handle an exception, Flask returns an HTTP 500 response without providing any specific information, like the traceback. Producing a generic error is a safe default behavior to avoid leaking any private information to the users in the error body.
The default 500 response is a simple HTML page along with the right status code:
$ curl http://localhost:5000/api
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>
When implementing microservices using JSON, it's a good practice to make sure that every response sent to the clients, including any exception, is JSON formatted. Consumers of your microservice will expect every response to be machine-parseable.
Flask lets you customize the app error handling via a couple of functions. The first one is the @app.errorhandler decorator, which works like @app.route. But instead of providing an endpoint, the decorator links a function to a specific error code.
In the following example, we use it to connect a function that will return a JSON-formatted error when Flask returns a 500 server response (any code exception):
from flask import Flask, jsonify
app = Flask(__name__)
@app.errorhandler(500)
def error_handling(error):
return jsonify({'Error': str(error)}, 500)
@app.route('/api')
def my_microservice():
raise TypeError("Some Exception")
if __name__ == '__main__':
app.run()
Flask will call this error view no matter what exception the code raises.
However, in case your application issues an HTTP 404 or any other 4xx or 5xx response, you will be back to the default HTML responses that Flask sends.
To make sure your app sends JSON for every 4xx and 50x, we need to register that function to each error code.
One place where you can find the list of errors is in the abort.mapping dict. In the following code snippet, we register the error_handling function to every error using app.register_error_handler, which is similar to the @app.errorhandler decorator:
from flask import Flask, jsonify, abort
from werkzeug.exceptions import HTTPException, default_exceptions
def JsonApp(app):
def error_handling(error):
if isinstance(error, HTTPException):
result = {'code': error.code, 'description':
error.description, 'message': str(error)}
else:
description = abort.mapping[500].description
result = {'code': 500, 'description': description,
'message': str(error)}
resp = jsonify(result)
resp.status_code = result['code']
return resp
for code in default_exceptions.keys():
app.register_error_handler(code, error_handling)
return app
app = JsonApp(Flask(__name__))
@app.route('/api')
def my_microservice():
raise TypeError("Some Exception")
if __name__ == '__main__':
app.run()
The JsonApp function wraps a Flask app instance, and sets up the custom JSON error handler for every 4xx and 50x error that might occur.
- 新編Visual Basic程序設(shè)計(jì)上機(jī)實(shí)驗(yàn)教程
- Kibana Essentials
- Vue.js 3.x從入門到精通(視頻教學(xué)版)
- Java從入門到精通(第4版)
- 數(shù)據(jù)結(jié)構(gòu)習(xí)題精解(C語(yǔ)言實(shí)現(xiàn)+微課視頻)
- 機(jī)械工程師Python編程:入門、實(shí)戰(zhàn)與進(jìn)階
- QTP自動(dòng)化測(cè)試進(jìn)階
- GeoServer Beginner's Guide(Second Edition)
- Asynchronous Android Programming(Second Edition)
- 大學(xué)計(jì)算機(jī)基礎(chǔ)實(shí)驗(yàn)指導(dǎo)
- Test-Driven Development with Django
- C專家編程
- Windows Embedded CE 6.0程序設(shè)計(jì)實(shí)戰(zhàn)
- Test-Driven JavaScript Development
- HTML5開發(fā)精要與實(shí)例詳解