diff --git a/CHANGELOG.md b/CHANGELOG.md index d6be5d1..24e7cff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## Unreleased +### Changed +- Properly handle database connection errors + ### [0.7.0] - 2018-11-07 ## Added - Ability to configure PostgreSQL database port with DATABASE_PORT environment variable (defaults to 5432) diff --git a/README.md b/README.md index a010a37..c6b7bed 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,6 @@ The item id is the *internal* id for an item. You can get these from the standar - Better logging - Tests -- Check if database exists (try/except) - Version API - Use JSON in PostgreSQL - Switch to [Python 3.6+ f-string syntax](https://realpython.com/python-f-strings/) diff --git a/dspace_statistics_api/database.py b/dspace_statistics_api/database.py index d240757..cb8640e 100644 --- a/dspace_statistics_api/database.py +++ b/dspace_statistics_api/database.py @@ -3,6 +3,7 @@ from .config import DATABASE_USER from .config import DATABASE_PASS from .config import DATABASE_HOST from .config import DATABASE_PORT +import falcon import psycopg2 import psycopg2.extras @@ -14,7 +15,13 @@ class DatabaseManager(): self._connection_uri = 'dbname={} user={} password={} host={} port={}'.format(DATABASE_NAME, DATABASE_USER, DATABASE_PASS, DATABASE_HOST, DATABASE_PORT) def __enter__(self): - self._connection = psycopg2.connect(self._connection_uri, cursor_factory=psycopg2.extras.DictCursor) + try: + self._connection = psycopg2.connect(self._connection_uri, cursor_factory=psycopg2.extras.DictCursor) + except psycopg2.OperationalError: + title = '500 Internal Server Error' + description = 'Could not connect to database' + raise falcon.HTTPInternalServerError(title, description) + return self._connection def __exit__(self, exc_type, exc_value, exc_traceback):