-
Notifications
You must be signed in to change notification settings - Fork 0
1.3.3 Kustom Halaman Error
Kustom Halaman Error adalah ketika kamu dalam mode debug=False/(Production) dan terjadi error pada halaman website baik 404 (Not Found), 403 (Forbidden) ataupun 500 (Internal Server Error). Agar terlihat lebih user friendly, kita dapat melakukan kustom pada halaman tersebut.
# app.py
from flask import Flask, render_template
...
@app.errorhandler(403)
def page_not_found(e):
return render_template('403.html'), 403
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(e)
return render_template('500.html'), 500errorhandler mengembalikan respon status kode 403, 404, dan 500. Jadi ketika terjadi error 404 maka akan mengakses halaman 404.html dan seterusnya. Selanjutnya, kita akan membuat file template error 403.html, 404.html, 500.html pada folder templates, sehingga struktur dari direktori nya akan terlihat seperti ini:
├── env/
| └── .....
├── templates/
| └── 403.html
| └── 404.html
| └── 500.html
| └── base.html
| └── navbar.html
| └── user.html
├── app.py
Status Kode 403 👇
# templates/403.html
{% extends 'base.html' %}
{% block title %}403 Forbidden{% endblock %}
{% block content %}
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-4">403 Forbidden</h1>
</div>
</div>
{% endblock %}Status Kode 404 👇
# templates/404.html
{% extends 'base.html' %}
{% block title %}404 Page Not Found{% endblock %}
{% block content %}
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-4">404 Page Not Found</h1>
</div>
</div>
{% endblock %}Status Kode 500 👇
# templates/500.html
{% extends 'base.html' %}
{% block title %}500 Internal Server Error{% endblock %}
{% block content %}
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-4">500 Internal Server Error</h1>
</div>
</div>
{% endblock %}Error pages ini akan terbaca ketika kamu merubah debug=False nanti ketika mengakses halaman yang salah, akan muncul custome page 404.html dan seterusnya.
Referensi :
- Miguel Grinberg - Flask Web Development, Developing Web Applications with Python