errorHandler

JSFunction errorHandler()

Express error handler middleware.

Catches all AppError instances and sends appropriate JSON responses. Unknown errors are logged and returned as 500 Internal Server Error.

Implementation

JSFunction errorHandler() =>
    ((JSAny? err, Request req, Response res, JSNextFunction next) {
      if (err == null) {
        next.call();
        return;
      }

// Try to extract the Dart error final dartError = err.dartify();

final (int status, Map<String, dynamic> body) = switch (dartError) { AppError e => (e.statusCode, e.toJson()), _ => ( 500, { 'success': false, 'error': { 'message': 'Internal server error', 'statusCode': 500, }, }, ), };

res ..status(status) ..jsonMap(body); }).toJS;