Exception Handling¶
Connexion allows you to register custom error handlers to convert Python Exceptions
into HTTP
problem responses.
You can register error handlers on:
The exception class to handle If this exception class is raised somewhere in your application or the middleware stack, it will be passed to your handler.
The HTTP status code to handle Connexion will raise
starlette.HTTPException
errors when it encounters any issues with a request or response. You can intercept these exceptions with specific status codes if you want to return custom responses.
from connexion import AsyncApp
from connexion.lifecycle import ConnexionRequest, ConnexionResponse
def not_found(request: ConnexionRequest, exc: Exception) -> ConnexionResponse:
return ConnexionResponse(status_code=404, body=json.dumps({"error": "NotFound"}))
app = AsyncApp(__name__)
app.add_error_handler(FileNotFoundError, not_found)
app.add_error_handler(404, not_found)
View a detailed reference of the add_error_handler
method
- AsyncApp.add_error_handler(code_or_exception: Union[int, Type[Exception]], function: Callable[[ConnexionRequest, Exception], Union[Awaitable[ConnexionResponse], ConnexionResponse]]) None
Register a callable to handle application errors.
- Parameters:
code_or_exception – An exception class or the status code of HTTP exceptions to handle.
function – Callable that will handle exception, may be async.
from connexion import FlaskApp
from connexion.lifecycle import ConnexionRequest, ConnexionResponse
def not_found(request: ConnexionRequest, exc: Exception) -> ConnexionResponse:
return ConnexionResponse(status_code=404, body=json.dumps({"error": "NotFound"}))
app = FlaskApp(__name__)
app.add_error_handler(FileNotFoundError, not_found)
app.add_error_handler(404, not_found)
View a detailed reference of the add_error_handler
method
- FlaskApp.add_error_handler(code_or_exception: Union[int, Type[Exception]], function: Callable[[ConnexionRequest, Exception], Union[Awaitable[ConnexionResponse], ConnexionResponse]]) None
Register a callable to handle application errors.
- Parameters:
code_or_exception – An exception class or the status code of HTTP exceptions to handle.
function – Callable that will handle exception, may be async.
Note
Warning
⚠️ The following is not recommended as it complicates the exception handling logic,
You can also register error handlers on the underlying flask application directly.
flask_app = app.app
flask_app.register_error_handler(FileNotFoundError, not_found)
flask_app.register_error_handler(404, not_found)
Error handlers registered this way:
Will only intercept exceptions thrown in the application, not in the Connexion middleware.
Can intercept exceptions before they reach the error handlers registered on the connexion app.
When registered on status code, will intercept only
werkzeug.exceptions.HTTPException
thrown by werkzeug / Flask notstarlette.exceptions.HTTPException
.
from asgi_framework import App
from connexion import ConnexionMiddleware
from connexion.lifecycle import ConnexionRequest, ConnexionResponse
def not_found(request: ConnexionRequest, exc: Exception) -> ConnexionResponse:
return ConnexionResponse(status_code=404, body=json.dumps({"error": "NotFound"}))
app = App(__name__)
app = ConnexionMiddleware(app)
app.add_error_handler(FileNotFoundError, not_found)
app.add_error_handler(404, not_found)
View a detailed reference of the add_error_handler
method
- ConnexionMiddleware.add_error_handler(code_or_exception: Union[int, Type[Exception]], function: Callable[[ConnexionRequest, Exception], Union[Awaitable[ConnexionResponse], ConnexionResponse]]) None
Register a callable to handle application errors.
- Parameters:
code_or_exception – An exception class or the status code of HTTP exceptions to handle.
function – Callable that will handle exception, may be async.
Note
This might not catch HTTPExceptions
with the same status code raised by
your wrapped ASGI/WSGI framework.
Note
Error handlers can be async
coroutines as well.
Default Exception Handling¶
By default connexion exceptions are JSON serialized according to Problem Details for HTTP APIs
Application can return errors using connexion.problem.problem
or raise exceptions that inherit
either from connexion.ProblemException
or one of its subclasses to achieve the same behavior.
Using this, we can rewrite the handler above:
from connexion.lifecycle import ConnexionRequest, ConnexionResponse
from connexion.problem import problem
def not_found(request: ConnexionRequest, exc: Exception) -> ConnexionResponse:
return problem(
title="NotFound",
detail="The requested resource was not found on the server",
status=404,
)
View a detailed reference of the problem
function
- connexion.problem.problem(status, title, detail, type=None, instance=None, headers=None, ext=None)¶
Returns a Problem Details error response.
- Parameters:
status (int) – The HTTP status code generated by the origin server for this occurrence of the problem.
title (str) – A short, human-readable summary of the problem type. It SHOULD NOT change from occurrence to occurrence of the problem, except for purposes of localisation.
detail (str) – An human readable explanation specific to this occurrence of the problem.
type – An absolute URI that identifies the problem type. When dereferenced, it SHOULD provide human-readable documentation for the problem type (e.g., using HTML). When this member is not present its value is assumed to be “about:blank”.
instance (str) – An absolute URI that identifies the specific occurrence of the problem. It may or may not yield further information if dereferenced.
headers (dict | None) – HTTP headers to include in the response
ext (dict | None) – Extension members to include in the body
- Type:
type: str
- Returns:
error response
- Return type:
ConnexionResponse
Connexion Exceptions¶
There are several exception types in connexion that contain extra information to help you render appropriate messages to your user beyond the default description and status code:
This module defines Exception classes used by Connexion to generate a proper response.
- exception connexion.exceptions.ConnexionException¶
Bases:
Exception
Base class for any exception thrown by the Connexion framework.
- exception connexion.exceptions.ResolverError¶
Bases:
LookupError
,ConnexionException
Error raised at startup when the resolver cannot find a view function for an endpoint in your specification, and no
resolver_error
is configured.
- exception connexion.exceptions.InvalidSpecification(message: str, validator: str = <unset>, path: Iterable[str | int] = (), cause: Exception | None = None, context=(), validator_value: Any = <unset>, instance: Any = <unset>, schema: Mapping[str, Any] | bool = <unset>, schema_path: Iterable[str | int] = (), parent: _Error | None = None, type_checker: _types.TypeChecker = <unset>)¶
Bases:
ValidationError
,ConnexionException
Error raised at startup when the provided specification cannot be validated.
- exception connexion.exceptions.MissingMiddleware¶
Bases:
ConnexionException
Error raised when you’re leveraging behavior that depends on a specific middleware, and that middleware is not part of your middleware stack.
- exception connexion.exceptions.ProblemException(*, status=500, title=None, detail=None, type=None, instance=None, headers=None, ext=None)¶
Bases:
HTTPException
,ConnexionException
This exception holds arguments that are going to be passed to the connexion.problem function to generate a proper response.
- exception connexion.exceptions.ClientProblem(status: int = 400, title: Optional[str] = None, *, detail: Optional[str] = None)¶
Bases:
ProblemException
Base exception for any 4XX error. Returns 400 by default, however
BadRequestProblem
should be preferred for 400 errors.
- exception connexion.exceptions.BadRequestProblem(detail=None)¶
Bases:
ClientProblem
Problem class for 400 Bad Request errors.
- exception connexion.exceptions.ExtraParameterProblem(*, param_type: str, extra_params: Iterable[str])¶
Bases:
BadRequestProblem
Problem class for 400 Bad Request errors raised when extra query or form parameters are detected and
strict_validation
is enabled.
- exception connexion.exceptions.TypeValidationError(schema_type: str, parameter_type: str, parameter_name: str)¶
Bases:
BadRequestProblem
Problem class for 400 Bad Request errors raised when path, query or form parameters with an incorrect type are detected.
- exception connexion.exceptions.Unauthorized(detail: str = "The server could not verify that you are authorized to access the URL requested. You either supplied the wrong credentials (e.g. a bad password), or your browser doesn't understand how to supply the credentials required.")¶
Bases:
ClientProblem
Problem class for 401 Unauthorized errors.
- exception connexion.exceptions.OAuthProblem(detail: str = "The server could not verify that you are authorized to access the URL requested. You either supplied the wrong credentials (e.g. a bad password), or your browser doesn't understand how to supply the credentials required.")¶
Bases:
Unauthorized
Problem class for 401 Unauthorized errors raised when there is an issue with the received OAuth headers.
- exception connexion.exceptions.OAuthResponseProblem(detail: str = "The server could not verify that you are authorized to access the URL requested. You either supplied the wrong credentials (e.g. a bad password), or your browser doesn't understand how to supply the credentials required.")¶
Bases:
OAuthProblem
Problem class for 401 Unauthorized errors raised when improper OAuth credentials are retrieved from your OAuth server.
- exception connexion.exceptions.Forbidden(detail: Optional[str] = None)¶
Bases:
HTTPException
Problem class for 403 Unauthorized errors.
- exception connexion.exceptions.OAuthScopeProblem(token_scopes: list, required_scopes: list)¶
Bases:
Forbidden
Problem class for 403 Unauthorized errors raised because of OAuth scope validation errors.
- exception connexion.exceptions.UnsupportedMediaTypeProblem(detail: Optional[str] = None)¶
Bases:
ClientProblem
Problem class for 415 Unsupported Media Type errors which are raised when Connexion receives a request with an unsupported media type header.
- exception connexion.exceptions.ServerError(status: int = 500, title: Optional[str] = None, *, detail: Optional[str] = None)¶
Bases:
ProblemException
Base exception for any 5XX error. Returns 500 by default, however
InternalServerError
should be preferred for 500 errors.
- exception connexion.exceptions.InternalServerError(detail: Optional[str] = None)¶
Bases:
ServerError
Problem class for 500 Internal Server errors.
- exception connexion.exceptions.NonConformingResponse(detail: Optional[str] = None)¶
Bases:
InternalServerError
Problem class for 500 Internal Server errors raised because of a returned response not matching the specification if response validation is enabled.
- exception connexion.exceptions.NonConformingResponseBody(detail: Optional[str] = None)¶
Bases:
NonConformingResponse
Problem class for 500 Internal Server errors raised because of a returned response body not matching the specification if response validation is enabled.
- exception connexion.exceptions.NonConformingResponseHeaders(detail: Optional[str] = None)¶
Bases:
NonConformingResponse
Problem class for 500 Internal Server errors raised because of a returned response headers not matching the specification if response validation is enabled.
- exception connexion.exceptions.ResolverProblem(status: int = 501, *, detail: Optional[str] = None)¶
Bases:
ServerError
Problem class for 501 Not Implemented errors raised when the resolver cannot find a view function to handle the incoming request.