From 6cd2ac9bd1eb27076bea0a043c8fab9e11d80bd3 Mon Sep 17 00:00:00 2001 From: sophie <16087569+sophie_liang@user.noreply.gitee.com> Date: Mon, 27 Apr 2026 17:23:32 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=85=A8=E5=B1=80=E5=BC=82?= =?UTF-8?q?=E5=B8=B8=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/__init__.py | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 102dd846..29760b3d 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -5,10 +5,11 @@ backend/app/__init__.py """ import logging -from flask import Flask +from flask import Flask, jsonify, request from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_cors import CORS +from werkzeug.exceptions import HTTPException from app.config import config db = SQLAlchemy() @@ -69,4 +70,30 @@ def create_app(config_name='default'): def _sync_persisted_settings(): _apply_persisted_settings(app) + def _should_return_json_error() -> bool: + if request.path.startswith('/api/'): + return True + accepted = request.headers.get('Accept', '') + return 'application/json' in accepted.lower() + + @app.errorhandler(HTTPException) + def _handle_http_exception(exc: HTTPException): + if not _should_return_json_error(): + return exc + message = exc.description or exc.name or 'HTTP error' + return jsonify({'error': str(message)}), int(exc.code or 500) + + @app.errorhandler(Exception) + def _handle_unexpected_exception(exc: Exception): + app.logger.exception( + 'Unhandled exception on %s %s', + request.method, + request.path, + exc_info=exc, + ) + if not _should_return_json_error(): + return '
Internal Server Error
', 500 + message = str(exc).strip() or 'Internal server error' + return jsonify({'error': message}), 500 + return app