handle method
Handles a request and returns a response without any HTTP layer.
This is the single request-processing path. Runtime adapters
(aim_server, aim_edge) build a Request, call this method, and
write the returned Response back to their platform.
This method:
- Creates a Context with the provided request
- Finds a matching route based on request method and path
- Executes the middleware chain
- Calls the appropriate handler (route handler or 404 handler)
- Handles errors using the registered error handler, then
onUnhandledError, then a plain 500 response. The fallback toonUnhandledErrorand the plain 500 also runs when the registered error handler itself throws.
The core never prints. Adapters that want to log unhandled errors pass
onUnhandledError.
Implementation
Future<Response> handle(
Request request, {
UnhandledErrorHandler<E>? onUnhandledError,
}) async {
final variables = _variablesFactory();
final context = Context<E>(request, variables);
try {
Route<E>? matchingRoute;
Map<String, String>? pathParams;
for (final route in _routes) {
if (route.method == request.method || route.method == '*') {
final params = route.match(request.path);
if (params != null) {
matchingRoute = route;
pathParams = params;
break;
}
}
}
Handler<E> finalHandler;
if (matchingRoute == null) {
finalHandler =
_notFoundHandler ??
(c) async => Response.notFound(body: 'Not Found');
} else {
finalHandler = (c) async {
pathParams!.forEach((key, value) {
c.set('param:$key', value);
});
return await matchingRoute!.handler(c);
};
}
return await _executeMiddlewareChain(context, finalHandler);
} catch (e, st) {
if (_errorHandler != null) {
try {
return await _errorHandler!(e, context);
} catch (handlerError, handlerStack) {
if (onUnhandledError != null) {
try {
return await onUnhandledError(
handlerError,
handlerStack,
context,
);
} catch (_) {
// fall through to the plain 500 below
}
}
return Response.internalServerError(body: 'Internal Server Error');
}
}
if (onUnhandledError != null) {
try {
return await onUnhandledError(e, st, context);
} catch (_) {
return Response.internalServerError(body: 'Internal Server Error');
}
}
return Response.internalServerError(body: 'Internal Server Error: $e');
}
}