python from sanic import Sanic from sanic.exceptions import SanicException from sanic.response import json app = Sanic(__name__) @app.exception(SanicException) async def handle_exceptions(request, exception): return json({'message': str(exception)}, status=500) @app.route('/') async def index(request): raise SanicException("Something went wrong") if __name__ == "__main__": app.run(host='0.0.0.0', port=8000) python from sanic import Sanic from sanic.exceptions import ServerError from sanic.response import json app = Sanic(__name__) @app.exception(ServerError) async def handle_server_error(request, exception): return json({'message': str(exception)}, status=500) @app.route('/') async def index(request): raise ServerError("Internal Server Error") if __name__ == "__main__": app.run(host='0.0.0.0', port=8000) python from sanic import Sanic from sanic.exceptions import ServerError from sanic.response import json app = Sanic(__name__) class CustomException(ServerError): pass @app.exception(CustomException) async def handle_custom_exception(request, exception): return json({'message': str(exception)}, status=500) @app.route('/') async def index(request): raise CustomException("Custom Exception") if __name__ == "__main__": app.run(host='0.0.0.0', port=8000) python from sanic import Sanic from sanic.response import json app = Sanic(__name__) @app.error async def handle_error(request, exception): return json({'message': str(exception)}, status=500) if __name__ == "__main__": app.run(host='0.0.0.0', port=8000)


上一篇:
下一篇:
切换中文