Skip to content

Commit

Permalink
fix(error): properly handle the 404 errors (#43)
Browse files Browse the repository at this point in the history
Signed-off-by: Nicolas Crocfer <nicolas.crocfer@corp.ovh.com>
  • Loading branch information
ncrocfer authored May 11, 2020
1 parent ba30a92 commit 5e81a80
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
14 changes: 13 additions & 1 deletion director/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from functools import partial
from pathlib import Path

from flask import Flask, Blueprint, jsonify
from flask import Flask, Blueprint, jsonify, request, render_template
from flask_json_schema import JsonValidationError

from director.api import api_bp
Expand Down Expand Up @@ -56,6 +56,9 @@ def create_app(
)
)

# Error handler
app.register_error_handler(404, lambda e: handle_not_found(e))

# Init extensions
db.init_app(app)
db.app = app
Expand Down Expand Up @@ -86,6 +89,15 @@ def create_app(
return app


def handle_not_found(e):
"""
Handle the "404 Not found" error in API and HTML.
"""
if request.path.startswith("/api"):
return jsonify(error=str(e)), 404
return render_template("404.html", error=e), 404


# Import director's submodules
def import_submodules(package, modules_to_import):
"""
Expand Down
8 changes: 8 additions & 0 deletions director/templates/404.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>404 Not Found</title>
</head>
<body>%% error %%</body>
</html>
30 changes: 30 additions & 0 deletions tests/test_views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
def test_view(client):
resp = client.get("/")
assert resp.status_code == 200
assert not resp.is_json
assert resp.mimetype == "text/html"
assert "<title>Celery Director</title>" in str(resp.data)


def test_404_view(client):
resp = client.get("/notfound")
assert resp.status_code == 404
assert not resp.is_json
assert resp.mimetype == "text/html"
assert "<title>404 Not Found</title>" in str(resp.data)


def test_api(client):
resp = client.get("/api/ping")
assert resp.status_code == 200
assert resp.is_json
assert resp.mimetype == "application/json"
assert resp.json == {"message": "pong"}


def test_404_api(client):
resp = client.get("/api/notfound")
assert resp.status_code == 404
assert resp.is_json
assert resp.mimetype == "application/json"
assert "404 Not Found" in resp.json["error"]

0 comments on commit 5e81a80

Please sign in to comment.