Jør*_*Vik 6 sql-server typescript 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);
};
Run Code Online (Sandbox Code Playgroud)
我试图 .catch 正在相关控制器中使用的请求,但似乎没有改变任何东西。请参阅下面的示例。
const users = await userRepository
.find()
.catch(error => {
console.log(error); // this is never triggered
});
Run Code Online (Sandbox Code Playgroud)
控制台中未注销任何错误消息。
这些是我在 TypeORM 中的连接选项
const users = await userRepository
.find()
.catch(error => {
console.log(error); // this is never triggered
});
Run Code Online (Sandbox Code Playgroud)
我还尝试将 createConnection 中的 requestTimeout 设置为 1000 (ms),结果相同。
小智 0
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;
}
}
Run Code Online (Sandbox Code Playgroud)
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
});
}
}
Run Code Online (Sandbox Code Playgroud)
将数据库名称更改为某个随机数据库时的结果我会在控制台中收到错误消息:
[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' }
Run Code Online (Sandbox Code Playgroud)
这就是你想要实现的目标吗?
| 归档时间: |
|
| 查看次数: |
1064 次 |
| 最近记录: |