From a3007f6cc06419c53b0abb077a1d776ce9d30622 Mon Sep 17 00:00:00 2001 From: Antonio Francisco Date: Mon, 6 Jul 2020 08:41:06 -0300 Subject: [PATCH] Method to handle HTTPExceptions New method to handle HTTPException now return a JSON with error code, name and description. Now NApps can simple raise a HTTPException setting a description to return in case of error. --- kytos/core/api_server.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/kytos/core/api_server.py b/kytos/core/api_server.py index a2bac2339..058f8991a 100644 --- a/kytos/core/api_server.py +++ b/kytos/core/api_server.py @@ -15,6 +15,7 @@ from flask import Flask, jsonify, request, send_file from flask_cors import CORS from flask_socketio import SocketIO, join_room, leave_room +from werkzeug.exceptions import HTTPException class APIServer: @@ -61,6 +62,22 @@ def __init__(self, app_name, listen='0.0.0.0', port=8181, # Update web-ui if necessary self.update_web_ui(force=False) + @self.app.errorhandler(HTTPException) + def handle_exception(e): + # pylint: disable=unused-variable, invalid-name + """Return a json for HTTP errors + + This handler allows NApps to return HTTP error messages + by raising a HTTPException. When raising the Exception, + create it with a description. + """ + response = jsonify({ + 'code': e.code, + 'name': e.name, + 'description': e.description + }) + return response, e.code + def _enable_websocket_rooms(self): socket = self.server socket.on_event('join', join_room)