from flask import request, render_template from app.utils.response_handler import ResponseHandler from app.utils.exceptions import APIException from app.constants.http_status import HTTPStatus from app.constants.messages import ErrorMessage from app.services.db_service import db import traceback def register_error_handlers(app): # Custom API Exception @app.errorhandler(APIException) def handle_api_exception(e): db.session.rollback() if request.path.startswith("/api"): return ResponseHandler.error( message=e.message, errors=e.errors, status_code=e.status_code ) return render_template("errors/500.html"), e.status_code # 404 @app.errorhandler(404) def handle_404(e): if request.path.startswith("/api"): return ResponseHandler.error( message=ErrorMessage.NOT_FOUND, status_code=HTTPStatus.NOT_FOUND ) return render_template("errors/404.html"), 404 # 500 @app.errorhandler(500) def handle_500(e): db.session.rollback() traceback.print_exc() if request.path.startswith("/api"): return ResponseHandler.error( message=ErrorMessage.INTERNAL_ERROR, status_code=HTTPStatus.INTERNAL_SERVER_ERROR ) return render_template("errors/500.html"), 500 # Catch All @app.errorhandler(Exception) def handle_general_exception(e): db.session.rollback() traceback.print_exc() if request.path.startswith("/api"): return ResponseHandler.error( message=ErrorMessage.INTERNAL_ERROR, status_code=HTTPStatus.INTERNAL_SERVER_ERROR ) return render_template("errors/500.html"), 500