[Frontend][Core] Standardize request error handling with VLLMError hierarchy (#49665)

Signed-off-by: Zach Zhu <zzqshu@126.com>
This commit is contained in:
Zach Zhu
2026-07-29 04:20:40 +00:00
committed by GitHub
parent f37f03db4a
commit 58f9659397
46 changed files with 370 additions and 248 deletions
+16 -20
View File
@@ -28,7 +28,6 @@ from vllm.engine.protocol import EngineClient
from vllm.entrypoints.chat_utils import load_chat_template
from vllm.entrypoints.launcher import serve_http
from vllm.entrypoints.openai.cli_args import make_arg_parser, validate_parsed_serve_args
from vllm.entrypoints.openai.engine.protocol import GenerationError
from vllm.entrypoints.openai.models.protocol import BaseModelPath
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
from vllm.entrypoints.serve.elastic_ep.middleware import ScalingMiddleware
@@ -42,20 +41,15 @@ from vllm.entrypoints.serve.utils.api_utils import (
)
from vllm.entrypoints.serve.utils.request_logger import RequestLogger
from vllm.entrypoints.serve.utils.server_utils import (
engine_error_handler,
exception_handler,
generation_error_handler,
get_uvicorn_log_config,
http_exception_handler,
lifespan,
log_response,
validation_exception_handler,
vllm_error_handler,
)
from vllm.exceptions import (
VLLMNotFoundError,
VLLMUnprocessableEntityError,
VLLMValidationError,
)
from vllm.exceptions import VLLMError
from vllm.logger import init_logger
from vllm.reasoning import ReasoningParserManager
from vllm.renderers.online_derenderer import OnlineDerenderer
@@ -67,7 +61,6 @@ from vllm.usage.usage_lib import UsageContext
from vllm.utils.argparse_utils import FlexibleArgumentParser
from vllm.utils.network_utils import is_valid_ipv6_address
from vllm.utils.system_utils import decorate_logs, set_ulimit
from vllm.v1.engine.exceptions import EngineDeadError, EngineGenerateError
from vllm.version import __version__ as VLLM_VERSION
prometheus_multiproc_dir: tempfile.TemporaryDirectory
@@ -291,23 +284,26 @@ def build_app(
allow_headers=args.allowed_headers,
)
# Exception handlers are registered in four layers:
# 1. framework errors raised by FastAPI/Starlette
# 2. vLLM-specific errors dispatched via a single ``VLLMError`` handler
# 3. fallback handlers for raw exceptions not yet migrated to ``VLLMError``
# 4. the raw ``Exception`` handler as a safety net
# Registering specific exception types (rather than only ``Exception``)
# ensures they are handled by ``ExceptionMiddleware`` (inside the Prometheus
# middleware) rather than ``ServerErrorMiddleware`` (outside it), so their
# status codes are recorded correctly.
app.exception_handler(HTTPException)(http_exception_handler)
app.exception_handler(RequestValidationError)(validation_exception_handler)
app.exception_handler(EngineGenerateError)(engine_error_handler)
app.exception_handler(EngineDeadError)(engine_error_handler)
app.exception_handler(GenerationError)(generation_error_handler)
# Register specific exception types so they are handled by
# ExceptionMiddleware (inside the Prometheus middleware) rather than
# ServerErrorMiddleware (outside it). Without this, these exceptions
# propagate through Prometheus as unhandled and get recorded as 5xx
# even though they result in 4xx responses to the client.
app.exception_handler(VLLMValidationError)(exception_handler)
app.exception_handler(VLLMUnprocessableEntityError)(exception_handler)
app.exception_handler(VLLMNotFoundError)(exception_handler)
app.exception_handler(VLLMError)(vllm_error_handler)
# TODO(zqzten): remove these fallback handlers after migration to VLLMError
app.exception_handler(ValueError)(exception_handler)
app.exception_handler(TypeError)(exception_handler)
app.exception_handler(OverflowError)(exception_handler)
app.exception_handler(NotImplementedError)(exception_handler)
app.exception_handler(Exception)(exception_handler)
# Ensure --api-key option from CLI takes precedence over VLLM_API_KEY
+2 -2
View File
@@ -19,7 +19,7 @@ from pydantic import (
from vllm.config.utils import replace
from vllm.entrypoints.chat_utils import make_tool_call_id
from vllm.exceptions import VLLMValidationError
from vllm.exceptions import VLLMServerError, VLLMValidationError
from vllm.logger import init_logger
from vllm.sampling_params import StructuredOutputsParams
from vllm.utils import random_uuid
@@ -404,7 +404,7 @@ class DeltaMessage(OpenAIBaseModel):
return data
class GenerationError(Exception):
class GenerationError(VLLMServerError):
"""raised when finish_reason indicates internal server error (500)"""
def __init__(self, message: str = "Internal server error"):
+18 -5
View File
@@ -28,7 +28,9 @@ def create_error_response(
)
from vllm.exceptions import (
VLLMClientError,
VLLMNotFoundError,
VLLMServerError,
VLLMUnprocessableEntityError,
VLLMValidationError,
)
@@ -45,8 +47,23 @@ def create_error_response(
err_type = "NotFoundError"
status_code = HTTPStatus.NOT_FOUND
param = None
elif isinstance(exc, VLLMClientError):
# Any other client-caused error defaults to 400.
err_type = "BadRequestError"
status_code = HTTPStatus.BAD_REQUEST
param = None
elif isinstance(exc, GenerationError):
err_type = "InternalServerError"
status_code = exc.status_code
param = None
elif isinstance(exc, VLLMServerError):
# Any other server-caused error defaults to 500.
err_type = "InternalServerError"
status_code = HTTPStatus.INTERNAL_SERVER_ERROR
param = None
# Fallback for raw exceptions not yet migrated to VLLMError.
# TODO(zqzten): remove these fallback handlers after migration to VLLMError
elif isinstance(exc, (ValueError, TypeError, OverflowError)):
# Common validation errors from user input
err_type = "BadRequestError"
status_code = HTTPStatus.BAD_REQUEST
param = None
@@ -54,10 +71,6 @@ def create_error_response(
err_type = "NotImplementedError"
status_code = HTTPStatus.NOT_IMPLEMENTED
param = None
elif isinstance(exc, GenerationError):
err_type = "InternalServerError"
status_code = exc.status_code
param = None
elif any(cls.__name__ == "TemplateError" for cls in type(exc).__mro__):
# jinja2.TemplateError and its subclasses (avoid importing jinja2)
err_type = "BadRequestError"
+11 -1
View File
@@ -31,7 +31,7 @@ from vllm.entrypoints.serve.utils.error_response import (
create_error_response,
sanitize_message,
)
from vllm.exceptions import VLLMValidationError
from vllm.exceptions import VLLMError, VLLMValidationError
from vllm.logger import init_logger
from vllm.utils.gc_utils import freeze_gc_heap
from vllm.v1.engine.exceptions import EngineDeadError, EngineGenerateError
@@ -325,6 +325,16 @@ async def log_response(request: Request, call_next):
return response
async def vllm_error_handler(req: Request, exc: VLLMError):
"""Dispatch a vLLM-specific error to the appropriate handler."""
if isinstance(exc, (EngineGenerateError, EngineDeadError)):
return await engine_error_handler(req, exc)
elif isinstance(exc, GenerationError):
return await generation_error_handler(req, exc)
else:
return await exception_handler(req, exc)
async def engine_error_handler(
req: Request, exc: EngineDeadError | EngineGenerateError
):