composer: Set up a custom HTTP error handler

Override flask's default error handler, because that return html. Return
JSON instead with the usual { "status": false, "errors": [ ... ] }
pattern.
This commit is contained in:
Lars Karlitski 2019-05-30 02:12:03 +02:00 committed by Alexander Todorov
parent 3587ed3663
commit 8ed910b29a
3 changed files with 29 additions and 0 deletions

View File

@ -16,6 +16,9 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# HTTP errors
HTTP_ERROR = "HTTPError"
# Returned from the API when either an invalid compose type is given, or not
# compose type is given.
BAD_COMPOSE_TYPE = "BadComposeType"

View File

@ -21,9 +21,11 @@ from collections import namedtuple
from flask import Flask, jsonify, redirect, send_from_directory
from glob import glob
import os
import werkzeug
from pylorax import vernum
from pylorax.api.crossdomain import crossdomain
from pylorax.api.errors import HTTP_ERROR
from pylorax.api.v0 import v0_api
from pylorax.sysutils import joinpaths
@ -79,4 +81,8 @@ def v0_status():
db_supported=True,
msgs=server.config["TEMPLATE_ERRORS"])
@server.errorhandler(werkzeug.exceptions.HTTPException)
def bad_request(error):
return jsonify(status=False, errors=[{ "id": HTTP_ERROR, "code": error.code, "msg": error.name }]), error.code
v0_api(server)

View File

@ -1553,6 +1553,26 @@ class ServerTestCase(unittest.TestCase):
self.assertTrue(len(data["errors"]) > 0)
self.assertEqual(data["errors"][0]["id"], "UnknownBlueprint")
def test_404(self):
"""Test that a 404 returns JSON"""
resp = self.server.get("/marmalade")
print(resp)
print(resp.data)
self.assertEqual(resp.status_code, 404)
self.assertEqual(json.loads(resp.data), {
"status": False,
"errors": [{ "id": "HTTPError", "code": 404, "msg": "Not Found" }]
})
def test_405(self):
"""Test that a 405 returns JSON"""
resp = self.server.post("/api/status")
self.assertEqual(resp.status_code, 405)
self.assertEqual(json.loads(resp.data), {
"status": False,
"errors": [{ "id": "HTTPError", "code": 405, "msg": "Method Not Allowed" }]
})
@contextmanager
def in_tempdir(prefix='tmp'):
"""Execute a block of code with chdir in a temporary location"""