Jelajahi Sumber

Better exception handling.

scossu 10 bulan lalu
induk
melakukan
ccafaeeea3
2 mengubah file dengan 25 tambahan dan 20 penghapusan
  1. 3 1
      scriptshifter/exceptions.py
  2. 22 19
      scriptshifter/rest_api.py

+ 3 - 1
scriptshifter/exceptions.py

@@ -9,9 +9,11 @@ class ApiError(Exception):
     status_code = 400
     msg = "An undefined error occurred."
 
-    def __init__(self, msg=None):
+    def __init__(self, msg=None, status_code=None):
         if msg is not None:
             self.msg = msg
+        if status_code is not None:
+            self.status_code = status_code
 
     def to_json(self):
         return {

+ 22 - 19
scriptshifter/rest_api.py

@@ -8,7 +8,6 @@ from os import environ, urandom
 from smtplib import SMTP
 
 from flask import Flask, jsonify, render_template, request
-from werkzeug.exceptions import BadRequest
 
 from scriptshifter import EMAIL_FROM, EMAIL_TO, SMTP_HOST, SMTP_PORT
 from scriptshifter.exceptions import ApiError
@@ -38,27 +37,29 @@ app = create_app()
 
 @app.errorhandler(ApiError)
 def handle_exception(e: ApiError):
-    return ({
-        "warnings": [
-            "ScriptShifter HTTP request failed with status code "
+    if e.status_code >= 500:
+        warnings = [
+            "An internal error occurred.",
+            "If the error persists, contact the technical support team."
+        ]
+    else:
+        warnings = [
+            "ScriptShifter API replied with status code "
             f"{e.status_code}: {e.msg}"
-        ],
-        "output": "",
-    }, e.status_code)
-
+        ]
+        if e.status_code >= 400:
+            warnings.append(
+                    "Please review your input before repeating this request.")
 
-@app.errorhandler(BadRequest)
-def handle_400(e):
+    body = {
+        "warnings": warnings,
+        "output": "",
+    }
     if logging.DEBUG >= logging.root.level:
-        body = {
-            "debug": {
-                "form_data": request.json or request.form,
-            }
+        body["debug"] = {
+            "form_data": request.json or request.form,
         }
-    else:
-        body = ""
-
-    return body, 400
+    return (body, e.status_code)
 
 
 @app.route("/", methods=["GET"])
@@ -121,7 +122,9 @@ def transliterate_req():
     try:
         out, warnings = transliterate(in_txt, lang, t_dir, capitalize, options)
     except (NotImplementedError, ValueError) as e:
-        return (str(e), 400)
+        raise ApiError(str(e), 400)
+    except Exception as e:
+        raise ApiError(str(e), 500)
 
     return {"output": out, "warnings": warnings}