renderError function
Report error and give the response for it, from the
ExceptionHandler of AppConfig. It is not sent yet.
Implementation
dynamic renderError(HttpRequest req, Object error, StackTrace stackTrace) {
/// `schema.parse()` in a controller: answer 422 like `req.validate()`
if (error is dv.ValidationException) {
error = ValidationException(message: error.errors, issues: error.issues);
}
ExceptionHandler handler = Dox().config.exceptionHandler;
dynamic payload = error;
try {
/// 4xx answers are the client's fault, only 5xx are reported
if (error is! IHttpException || error.code >= 500) {
handler.reportFor(req, error, stackTrace);
}
/// the head is out (a flush or a stream, eg. server-sent events): the
/// status and headers can not change, and an error text would land
/// inside the body. the error is reported, and the answer just ends.
/// the same when the handler took over and started its answer.
if (responseTakenOver(req)) {
/// took over, started its answer, then threw. Nothing else ends a
/// taken over answer, so end it here or the client waits forever.
if (answerStarted(req.response)) {
_endQuietly(req.response);
return null;
}
/// took over, then threw before it wrote anything: Dox answers
releaseTakeOver(req);
}
if (headSent(req.response)) return null;
/// the route renders its own errors (`Route.renderErrorsWith`)
DoxRequest? doxReq = _renderersUsed ? _withRenderer[req] : null;
RouteErrorRenderer? renderer = doxReq?.route.errorRenderer;
if (renderer != null) {
DoxResponse? custom = renderer(error, doxReq!);
if (custom != null) return custom;
if (responseTakenOver(req)) return null;
}
payload = handler.render(error, req);
} catch (handlerError, handlerStack) {
/// a broken handler must not leave the client waiting.
/// send the default answer for the first error.
Logger.danger(
'ExceptionHandler failed: $handlerError\n$handlerStack',
null,
'error',
);
}
if (identical(payload, error)) payload = _htmlPage(req, error, stackTrace);
return payload;
}