Browse Source

Fix error handling.

scossu 4 months ago
parent
commit
af2873b914
3 changed files with 14 additions and 24 deletions
  1. 2 2
      scriptshifter/exceptions.py
  2. 5 2
      scriptshifter/hooks/hebrew/dicta_api.py
  3. 7 20
      scriptshifter/rest_api.py

+ 2 - 2
scriptshifter/exceptions.py

@@ -22,9 +22,9 @@ class ApiError(Exception):
 
 class ConfigError(ApiError):
     """ Raised when a malformed configuration is detected. """
-    pass
+    status_code = 500
 
 
 class UpstreamError(ApiError):
     """ Raised when an external service responds with an error code. """
-    pass
+    status_code = 500

+ 5 - 2
scriptshifter/hooks/hebrew/dicta_api.py

@@ -2,7 +2,7 @@ from os import environ
 
 from requests import post
 
-from scriptshifter.exceptions import BREAK
+from scriptshifter.exceptions import BREAK, UpstreamError
 from scriptshifter.tools import capitalize
 
 EP = environ.get("TXL_DICTA_EP")
@@ -20,7 +20,10 @@ def s2r_post_config(ctx):
                 "data": ctx.src,
                 "genre": ctx.options.get("genre", DEFAULT_GENRE)
             })
-    rsp.raise_for_status()
+    try:
+        rsp.raise_for_status()
+    except Exception:
+        raise UpstreamError("Error received from Dicta service.")
 
     rom = rsp.json().get("transliteration")
 

+ 7 - 20
scriptshifter/rest_api.py

@@ -7,11 +7,7 @@ from os import environ, urandom
 
 from flask import Flask, jsonify, render_template, request
 
-<<<<<<< HEAD
 from scriptshifter.exceptions import ApiError
-=======
-# from scriptshifter.exceptions import ApiError
->>>>>>> 7e9bbf5e0854f7fd8325abc809b17b50ff927038
 from scriptshifter.tables import list_tables, load_table
 from scriptshifter.trans import transliterate
 
@@ -36,24 +32,15 @@ def create_app():
 app = create_app()
 
 
-<<<<<<< HEAD
 @app.errorhandler(ApiError)
 def handle_exception(e: ApiError):
-    rsp = e.get_response()
-    rsp.data = dumps({
-        "content": e.to_json(),
-        "status_code": e.status_code
-    })
-
-    return rsp
-=======
-#@app.exception_handler(ApiError)
-#def handle_exception(request: Request, e: ApiError):
-#    return JSONResponse(
-#        content=e.to_json(),
-#        status_code=e.status_code
-#    )
->>>>>>> 7e9bbf5e0854f7fd8325abc809b17b50ff927038
+    return ({
+        "warnings": [
+            "ScriptShifter HTTP request failed with status code "
+            f"{e.status_code}: {e.msg}"
+        ],
+        "output": "",
+    }, e.status_code)
 
 
 @app.route("/", methods=["GET"])