handleError method

Future handleError(
  1. Request request,
  2. dynamic caughtValue,
  3. StackTrace trace
)

Sends an HTTP response for a request that yields an exception or error.

When this controller encounters an exception or error while handling request, this method is called to send the response. By default, it attempts to send a 500 Server Error response and logs the error and stack trace to logger.

Note: If caughtValue's implements HandlerException, this method is not called.

If you override this method, it must not throw.

Implementation

Future handleError(
  Request request,
  dynamic caughtValue,
  StackTrace trace,
) async {
  if (caughtValue is HTTPStreamingException) {
    logger.severe(
      request.toDebugString(includeHeaders: true),
      caughtValue.underlyingException,
      caughtValue.trace,
    );

    request.response.close().catchError((_) => null);

    return;
  }

  try {
    final body = includeErrorDetailsInServerErrorResponses
        ? {
            "controller": "$runtimeType",
            "error": "$caughtValue.",
            "stacktrace": trace.toString()
          }
        : null;

    final response = Response.serverError(body: body)
      ..contentType = ContentType.json;

    await _sendResponse(request, response, includeCORSHeaders: true);

    logger.severe(
      request.toDebugString(includeHeaders: true),
      caughtValue,
      trace,
    );
  } catch (e) {
    logger.severe("Failed to send response, draining request. Reason: $e");

    request.raw.drain().catchError((_) => null);
  }
}