From 002f6374ba8f447cbcf544bd82ef4bd53f95c5a0 Mon Sep 17 00:00:00 2001 From: Munyoki Kilyungi Date: Wed, 14 Feb 2024 14:58:14 +0300 Subject: Handle sparql errors at the app level. Signed-off-by: Munyoki Kilyungi --- gn3/errors.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/gn3/errors.py b/gn3/errors.py index ec0088d..3a2f781 100644 --- a/gn3/errors.py +++ b/gn3/errors.py @@ -1,7 +1,17 @@ """Handle application level errors.""" import traceback +from http.client import RemoteDisconnected +from urllib.error import URLError from sqlite3 import OperationalError +from SPARQLWrapper.SPARQLExceptions import ( + EndPointInternalError, + EndPointNotFound, + QueryBadFormed, + SPARQLWrapperException, + URITooLong, + Unauthorized +) from werkzeug.exceptions import NotFound from flask import Flask, jsonify, current_app from authlib.oauth2.rfc6749.errors import OAuth2Error @@ -15,6 +25,7 @@ def add_trace(exc: Exception, jsonmsg: dict) -> dict: "error-trace": "".join(traceback.format_exception(exc)) } + def page_not_found(pnf): """Generic 404 handler.""" return jsonify(add_trace(pnf, { @@ -22,6 +33,14 @@ def page_not_found(pnf): "error_description": pnf.description })), 404 +def internal_server_error(pnf): + """Generic 404 handler.""" + return jsonify(add_trace(pnf, { + "error": pnf.name, + "error_description": pnf.description + })), 500 + + def handle_authorisation_error(exc: AuthorisationError): """Handle AuthorisationError if not handled anywhere else.""" current_app.logger.error(exc) @@ -46,9 +65,35 @@ def handle_sqlite3_errors(exc: OperationalError): "error_description": exc.args[0], }), 500 +def handle_sparql_errors(exc: SPARQLWrapperException): + """Handle sqlite3 errors if not handled anywhere else.""" + current_app.logger.error(exc) + __code = { + EndPointInternalError: 500, + EndPointNotFound: 400, + QueryBadFormed: 400, + Unauthorized: 401, + URITooLong: 414, + } + return jsonify({ + "error": exc.msg, + "error_description": str(exc), + }), __code.get(exc) + + def register_error_handlers(app: Flask): """Register application-level error handlers.""" app.register_error_handler(NotFound, page_not_found) app.register_error_handler(OAuth2Error, handle_oauth2_errors) app.register_error_handler(OperationalError, handle_sqlite3_errors) app.register_error_handler(AuthorisationError, handle_authorisation_error) + app.register_error_handler(RemoteDisconnected, internal_server_error) + app.register_error_handler(URLError, internal_server_error) + for exc in ( + EndPointInternalError, + EndPointNotFound, + QueryBadFormed, + URITooLong, + Unauthorized + ): + app.register_error_handler(exc, handle_sparql_errors) -- cgit v1.2.3