| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | |
| 4 | """vLLM Exception handlers are registered in four layers: |
| 5 | 1. framework errors raised by FastAPI/Starlette |
| 6 | 2. vLLM-specific errors dispatched via a single ``VLLMError`` handler |
| 7 | 3. fallback handlers for raw exceptions not yet migrated to ``VLLMError`` |
| 8 | 4. the raw ``Exception`` handler as a safety net |
| 9 | Registering specific exception types (rather than only ``Exception``) |
| 10 | ensures they are handled by ``ExceptionMiddleware`` (inside the Prometheus |
| 11 | middleware) rather than ``ServerErrorMiddleware`` (outside it), so their |
| 12 | status codes are recorded correctly. |
| 13 | """ |
| 14 | |
| 15 | from fastapi import FastAPI, HTTPException |
| 16 | from fastapi.exceptions import RequestValidationError |
| 17 | |
| 18 | from vllm.exceptions import VLLMError |
| 19 | |
| 20 | from .handlers.exception import exception_handler |
| 21 | from .handlers.http import http_exception_handler |
| 22 | from .handlers.validation import validation_exception_handler |
| 23 | from .handlers.vllm_error import vllm_error_handler |
| 24 | |
| 25 | |
| 26 | def init_exception_handler(app: FastAPI): |
| 27 | # 1. framework errors raised by FastAPI/Starlette |
| 28 | app.exception_handler(HTTPException)(http_exception_handler) |
| 29 | app.exception_handler(RequestValidationError)(validation_exception_handler) |
| 30 | |
| 31 | # 2. vLLM-specific errors dispatched via a single ``VLLMError`` handler |
| 32 | app.exception_handler(VLLMError)(vllm_error_handler) |
| 33 | |
| 34 | # 3. fallback handlers for raw exceptions not yet migrated to ``VLLMError`` |
| 35 | # TODO(zqzten): remove these fallback handlers after migration to VLLMError |
| 36 | app.exception_handler(ValueError)(exception_handler) |
| 37 | app.exception_handler(TypeError)(exception_handler) |
| 38 | app.exception_handler(OverflowError)(exception_handler) |
| 39 | app.exception_handler(NotImplementedError)(exception_handler) |
| 40 | |
| 41 | # 4. the raw ``Exception`` handler as a safety net |
| 42 | app.exception_handler(Exception)(exception_handler) |