This guide explains how to handle errors effectively in your Pyvider provider.
🤖 AI-Generated Content
This documentation was generated with AI assistance and is still being audited. Some, or potentially a lot, of this information may be inaccurate. Learn more.
frompyvider.exceptionsimportResourceError,ProviderConfigurationErrorasyncdefcreate_server(config):ifnotconfig.name:raiseResourceError("Server name is required")try:server=awaitapi.create_server(config.name)returnserverexceptAPIErrorase:raiseResourceError(f"Failed to create server: {e}")
frompyvider.providersimportBaseProviderfrompyvider.exceptionsimportProviderConfigurationErrorclassMyProvider(BaseProvider):asyncdefconfigure(self,config:dict)->None:ifnotconfig.get("api_key"):raiseProviderConfigurationError("api_key is required")ifnotconfig["api_key"].startswith("sk_"):raiseProviderConfigurationError("Invalid API key format")try:self.client=APIClient(config["api_key"])awaitself.client.test_connection()exceptConnectionErrorase:raiseProviderConfigurationError(f"Failed to connect to API: {e}")
try:result=awaitexternal_api.call()exceptExternalAPIErrorase:raiseResourceError(f"External API call failed: {e}",details={"api_error_code":e.code,"retry_after":e.retry_after})
asyncdef_validate_config(self,config:ServerConfig)->list[str]:"""Validate configuration and return error list."""errors=[]ifnotconfig.name:errors.append("name is required")ifnot1<=config.port<=65535:errors.append(f"port must be 1-65535, got {config.port}")ifconfig.memory_gb<1:errors.append(f"memory_gb must be >= 1, got {config.memory_gb}")returnerrors
asyncdef_update_apply(self,ctx:ResourceContext):updated_fields=[]try:ifctx.config.name!=ctx.state.name:awaitapi.update_name(ctx.state.id,ctx.config.name)updated_fields.append("name")ifctx.config.size!=ctx.state.size:awaitapi.update_size(ctx.state.id,ctx.config.size)updated_fields.append("size")returnawaitself.read(ctx)exceptAPIErrorase:raiseResourceError(f"Update failed after updating: {', '.join(updated_fields)}. "f"Error: {e}. "f"Resource may be in inconsistent state.")
asyncdef_delete_apply(self,ctx:ResourceContext):errors=[]# Try to delete dependent resourcesfordepinctx.state.dependencies:try:awaitapi.delete_dependency(dep.id)exceptAPIErrorase:errors.append(f"Failed to delete {dep.type}{dep.id}: {e}")# Delete main resourcetry:awaitapi.delete_resource(ctx.state.id)exceptAPIErrorase:errors.append(f"Failed to delete resource: {e}")iferrors:raiseResourceError(f"Deletion completed with errors:\n"+"\n".join(f" - {err}"forerrinerrors))