Files
loongyan/bin/middleware/exception_handler.dart
2026-03-12 21:24:49 +08:00

44 lines
1.5 KiB
Dart

import 'package:shelf/shelf.dart';
import 'dart:io';
/// 全局异常处理中间件
/// 捕获所有未处理的异常并返回适当的 HTTP 响应
Middleware exceptionHandler() {
return (Handler innerHandler) {
return (Request request) async {
try {
return await innerHandler(request);
} on FormatException catch (e) {
// 处理参数格式错误,如无效的 ID
return Response.badRequest(
body: 'Invalid parameter format: ${e.message}',
headers: {'content-type': 'text/plain'},
);
} on PathNotFoundException catch (e) {
// 处理路径未找到
return Response.notFound('Resource not found: ${e.message}');
} on FileSystemException catch (e) {
// 处理文件系统错误
return Response.internalServerError(
body: 'File system error: ${e.message}',
headers: {'content-type': 'text/plain'},
);
} on Exception catch (e) {
// 处理其他已知异常
return Response.internalServerError(
body: 'Internal server error: ${e.toString()}',
headers: {'content-type': 'text/plain'},
);
} catch (e, stackTrace) {
// 处理未知异常
print('Unhandled exception: $e');
print('Stack trace: $stackTrace');
return Response.internalServerError(
body: 'An unexpected error occurred',
headers: {'content-type': 'text/plain'},
);
}
};
};
}