我想创建一个自定义异常过滤器来处理不同类型的 TypeORM 错误。我查看了TypeORM 错误类,似乎 TypeORM 中没有像MongoError这样的东西。
我想做一些类似于1FpGLLjZSZMx6k 的答案的东西,这就是我到目前为止所做的。
import { QueryFailedError } from 'typeorm';
@Catch(QueryFailedError)
export class QueryFailedExceptionFilter implements ExceptionFilter {
catch(exception: QueryFailedError, host: ArgumentsHost) {
const context = host.switchToHttp();
const response = context.getResponse<Response>();
const request = context.getRequest<Request>();
const { url } = request;
const { name } = exception;
const errorResponse = {
path: url,
timestamp: new Date().toISOString(),
message: name,
};
response.status(HttpStatus.BAD_REQUEST).json(errorResponse);
}
}
例如,如果我需要捕获另一个错误EntityNotFoundError,我必须编写相同的代码,这是一项非常繁琐的任务。
如果我可以通过如下所示的单个过滤器处理错误,那就太好了。有任何想法吗?
@Catch(TypeORMError)
export class EntityNotFoundExceptionFilter implements ExceptionFilter {
catch(exception: MongoError, host: ArgumentsHost) {
switch (exception.code) {
case some error code:
// handle error
}
}
}
小唯快跑啊
白猪掌柜的
相关分类