Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix: improve error messages for custom credential service failures (#5281)
Shuchang Zheng5aa1f2fb7c56
diff --git a/skyvern/exceptions.py b/skyvern/exceptions.pyindex 91f0436fa..3f70aae0c 100644--- a/skyvern/exceptions.py+++ b/skyvern/exceptions.py@@ -656,6 +656,9 @@ class NoSelectableElementFound(SkyvernException):class HttpException(SkyvernException):def __init__(self, status_code: int, url: str, msg: str | None = None) -> None:+ self.status_code = status_code+ self.url = url+ self.error_message = msgsuper().__init__(f"HTTP Exception, status_code={status_code}, url={url}" + (f", msg={msg}" if msg else ""))diff --git a/skyvern/forge/sdk/api/custom_credential_client.py b/skyvern/forge/sdk/api/custom_credential_client.pyindex 1036d3c1e..1093f47af 100644--- a/skyvern/forge/sdk/api/custom_credential_client.py+++ b/skyvern/forge/sdk/api/custom_credential_client.py@@ -3,7 +3,7 @@ from typing import Anyimport structlogfrom skyvern.exceptions import HttpException-from skyvern.forge.sdk.core.aiohttp_helper import aiohttp_delete, aiohttp_get_json, aiohttp_post+from skyvern.forge.sdk.core.aiohttp_helper import aiohttp_requestfrom skyvern.forge.sdk.schemas.credentials import (CredentialItem,CredentialType,@@ -69,6 +69,18 @@ class CustomCredentialAPIClient:else:raise TypeError(f"Unsupported credential type: {type(credential)}")+ @staticmethod+ def _format_error_response(response_body: Any) -> str:+ """Extract a human-readable error message from an HTTP error response body."""+ if isinstance(response_body, dict):+ for key in ["message", "error", "detail", "error_message"]:+ if key in response_body and response_body[key]:+ return str(response_body[key])+ return str(response_body)+ if isinstance(response_body, str) and response_body.strip():+ return response_body.strip()+ return ""+def _api_response_to_credential(self, credential_data: dict[str, Any], name: str, item_id: str) -> CredentialItem:"""Convert API response to Skyvern CredentialItem."""credential_type = credential_data.get("type")@@ -169,25 +181,38 @@ class CustomCredentialAPIClient:)try:- response = await aiohttp_post(+ status_code, _, response_body = await aiohttp_request(+ method="POST",url=url,- data=payload,headers=headers,- raise_exception=True,+ data=payload,)- if not response:- raise HttpException(500, url, "Empty response from custom credential API")+ if status_code < 200 or status_code >= 300:+ error_detail = self._format_error_response(response_body)+ msg = f"HTTP {status_code}"+ if error_detail:+ msg += f": {error_detail}"+ LOG.error(+ "Custom credential API returned error",+ url=url,+ status_code=status_code,+ response_body=response_body,+ )+ raise HttpException(status_code, url, msg)++ if not response_body or not isinstance(response_body, dict):+ raise HttpException(500, url, "Empty or invalid response from custom credential API")# Extract credential ID from response- credential_id = response.get("id")+ credential_id = response_body.get("id")if not credential_id:LOG.error("Custom credential API response missing id field",url=url,- response=response,+ response=response_body,)- raise HttpException(500, url, "Invalid response format from custom credential API")+ raise HttpException(500, url, "Invalid response format from custom credential API: missing 'id' field")LOG.info("Successfully created credential via custom API",@@ -234,13 +259,26 @@ class CustomCredentialAPIClient:)try:- response = await aiohttp_get_json(+ status_code, _, response_body = await aiohttp_request(+ method="GET",url=url,headers=headers,- raise_exception=True,)- if not response:+ if status_code < 200 or status_code >= 300:+ error_detail = self._format_error_response(response_body)+ msg = f"HTTP {status_code}"+ if error_detail:+ msg += f": {error_detail}"+ LOG.error(+ "Custom credential API returned error",+ url=url,+ status_code=status_code,+ response_body=response_body,+ )+ raise HttpException(status_code, url, msg)++ if not response_body or not isinstance(response_body, dict):raise HttpException(404, url, f"Credential not found: {credential_id}")LOG.info(@@ -249,7 +287,7 @@ class CustomCredentialAPIClient:credential_id=credential_id,)- return self._api_response_to_credential(response, name, credential_id)+ return self._api_response_to_credential(response_body, name, credential_id)except HttpException:raise@@ -283,12 +321,25 @@ class CustomCredentialAPIClient:)try:- await aiohttp_delete(+ status_code, _, response_body = await aiohttp_request(+ method="DELETE",url=url,headers=headers,- raise_exception=True,)+ if status_code < 200 or status_code >= 300:+ error_detail = self._format_error_response(response_body)+ msg = f"HTTP {status_code}"+ if error_detail:+ msg += f": {error_detail}"+ LOG.error(+ "Custom credential API returned error on delete",+ url=url,+ status_code=status_code,+ response_body=response_body,+ )+ raise HttpException(status_code, url, msg)+LOG.info("Successfully deleted credential via custom API",url=url,diff --git a/skyvern/forge/sdk/routes/credentials.py b/skyvern/forge/sdk/routes/credentials.pyindex 2e249197a..fd756262f 100644--- a/skyvern/forge/sdk/routes/credentials.py+++ b/skyvern/forge/sdk/routes/credentials.py@@ -33,6 +33,7 @@ import structlogfrom fastapi import BackgroundTasks, Body, Depends, HTTPException, Path, Queryfrom skyvern.config import settings+from skyvern.exceptions import HttpException as SkyvernHttpExceptionfrom skyvern.forge import appfrom skyvern.forge.sdk.db.enums import OrganizationAuthTokenTypefrom skyvern.forge.sdk.executor.factory import AsyncExecutorFactory@@ -303,7 +304,15 @@ async def create_credential() -> CredentialResponse:credential_service = await _get_credential_vault_service(vault_type_override=data.vault_type)- credential = await credential_service.create_credential(organization_id=current_org.organization_id, data=data)+ try:+ credential = await credential_service.create_credential(organization_id=current_org.organization_id, data=data)+ except SkyvernHttpException as e:+ detail = (+ f"Custom credential service returned {e.error_message}"+ if e.error_message+ else f"Custom credential service returned HTTP {e.status_code}"+ )+ raise HTTPException(status_code=502, detail=detail)if credential.vault_type == CredentialVaultType.BITWARDEN:# Early resyncing the Bitwarden vault@@ -1233,10 +1242,18 @@ async def update_credential(old_item_id = existing_credential.item_id- updated_credential = await credential_service.update_credential(- credential=existing_credential,- data=data,- )+ try:+ updated_credential = await credential_service.update_credential(+ credential=existing_credential,+ data=data,+ )+ except SkyvernHttpException as e:+ detail = (+ f"Custom credential service returned {e.error_message}"+ if e.error_message+ else f"Custom credential service returned HTTP {e.status_code}"+ )+ raise HTTPException(status_code=502, detail=detail)# Schedule background cleanup of old vault item if the item_id changedif old_item_id != updated_credential.item_id:@@ -1298,7 +1315,15 @@ async def delete_credential(if not credential_service:raise HTTPException(status_code=400, detail="Unsupported credential storage type")- await credential_service.delete_credential(credential)+ try:+ await credential_service.delete_credential(credential)+ except SkyvernHttpException as e:+ detail = (+ f"Custom credential service returned {e.error_message}"+ if e.error_message+ else f"Custom credential service returned HTTP {e.status_code}"+ )+ raise HTTPException(status_code=502, detail=detail)# Schedule background cleanup if the service implements itif vault_type != CredentialVaultType.CUSTOM: