error function

Middleware error({
  1. bool debug = false,
  2. ErrorHandler? errorHandler,
})

Middleware which catches errors thrown by inner handlers and returns a response with a 500 status code.

If debug is true, the error message and stack trace are returned in the response body. If debug is false (the default), a generic error message is returned.

Implementation

Middleware error({bool debug = false, ErrorHandler? errorHandler}) {
  Handler middleware(Handler innerHandler) {
    Future<Response> handler(Request request) async {
      try {
        return await innerHandler(request);
      } on HijackException {
        rethrow;
      } catch (error, stackTrace) {
        if (debug) {
          var accept = request.headers['accept'];

          if (accept != null && accept.contains('text/html')) {
            const headers = <String, String>{'content-type': 'text/html'};

            var trace = Trace.from(stackTrace);
            var body = _render(error, trace);
            return Response.internalServerError(body: body, headers: headers);
          }

          var trace = Trace.format(stackTrace);
          return Response.internalServerError(body: '$error\n$trace');
        }

        if (errorHandler == null) {
          return Response.internalServerError();
        }

        return errorHandler(request, error, stackTrace);
      }
    }

    return handler;
  }

  return middleware;
}