sql-server - TypeORM 处理数据库中断
问题描述
假设我的 MSSQL 服务器崩溃了,我的应用程序客户端从 API 请求了一些东西。现在它只会旋转,直到 Express 超时未回答的请求。
在 TypeORM 中启用日志记录后,我可以看到相关查询已执行。
我宁愿返回一个 API 响应,通知客户端数据库无法访问。
这是我的用户控制器中的实际代码
public static listAll = async (req: Request, res: Response) => {
const userRepository = getRepository(User);
const users = await userRepository
.find()
res.send(users);
};
我试图 .catch 相关控制器中正在使用的请求,但似乎没有任何改变。请参见下面的示例。
const users = await userRepository
.find()
.catch(error => {
console.log(error); // this is never triggered
});
控制台中未注销任何错误消息。
这些是我在 TypeORM 中的连接选项
createConnection({
type: 'mssql',
host: process.env.TYPEORM_HOST,
port: parseInt(process.env.TYPEORM_PORT, 0),
username: process.env.TYPEORM_USERNAME,
password: process.env.TYPEORM_PASSWORD,
database: process.env.TYPEORM_DATABASE,
synchronize: true,
logging: true,
entities: models,
cli: {
entitiesDir: 'src/entity',
migrationsDir: 'src/migration',
subscribersDir: 'src/subscriber',
},
})
.then(connection => {
const server = http.createServer(App);
server.listen({ port: `${process.env.APP_PORT}` }, () => {
console.log(` Server ready at http://${process.env.TYPEORM_HOST}:${process.env.APP_PORT}`);
});
if (connection.isConnected) {
console.log(`Database ${connection.options.database} connected`);
}
})
.catch(error => console.log(error));
我还尝试将 createConnection 中的 requestTimeout 设置为 1000(毫秒),结果相同。
解决方案
export default class App {
public app: express.Application;
public db: Connection;
constructor() {
this.app = express();
this.appConfiguration();
}
public async appConfiguration() {
try {
this.db = await Database.init();
// Make use of JSON Body
this.app.use(bodyParser.json());
// Inits Routes
Routes.init(this.app);
} catch(err) {
console.log('database is not reachable, see error:', err)
};
}
public getApp(): express.Application {
return this.app;
}
}
Database.init() 用于创建与数据库的连接:
export class Database {
public static init() {
return createConnection({
type: "postgres",
host: process.env.TYPEORM_HOST,
port: parseInt(process.env.TYPEORM_PORT),
database: process.env.TYPEORM_DATABASE,
username: process.env.TYPEORM_USERNAME,
password: process.env.TYPEORM_PASSWORD,
entities: [
User
],
synchronize: process.env.TYPEORM_SYNCHRONIZE == "true" ? true : false,
logging: process.env.TYPEORM_LOGGING == "true" ? true : false
});
}
}
将数据库名称更改为某个随机数据库时的结果我将在控制台中收到错误消息:
[nodemon] starting `ts-node src/server.ts`
Server listening on port 5000
database is not reachable, see error:
{ error: database "express_text_typeorms" does not exist
at Connection.parseE
at Connection.parseMessage
at Socket.<anonymous>
at Socket.emit (events.js:198:13)
at Socket.EventEmitter.emit (domain.js:448:20)
at addChunk (_stream_readable.js:288:12)
at readableAddChunk (_stream_readable.js:269:11)
at Socket.Readable.push (_stream_readable.js:224:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
name: 'error',
length: 106,
severity: 'FATAL',
code: '3D000',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'postinit.c',
line: '890',
routine: 'InitPostgres' }
这就是你想要达到的吗?
推荐阅读
- python - pygame KEYUP 只注册 KEYDOWN
- laravel - Laravel Mix - 是否需要链接来确保执行顺序?
- arrays - 如何引用而不是复制另一个选项卡中的数据?
- android - 基于 App Variant 构建配置(BuildType + Flavor)
- c# - DateTimeOffset:DateTime 是本地时间还是 UTC 时间?
- batch-file - 用于弹出 USB 驱动器的 .BAT 命令(卸载、移除 - 您选择正确的动词)
- docker - 如何在 nginx 容器中启动 syslogd
- php - Php json _decode function returns null on long data
- angular - TypeError:无法读取未定义的属性“returnValue”
- javascript - 如何在内部使用两个调度来开玩笑测试 redux-thunk 动作?