在业务处理中发生错误,在官网的示例中没有具体的typeorm异常捕获,可以通过以下方式处理。
/// test.service.ts 业务处理
@Injectable()
export class TestService{
constructor(@InjectRepository(Test) private readonly test:Repository<Test>){}
async doSomething(id){
const test=new Test()
// id可能为undefined,在这里会throw一个错误
await this.test.update(id,test)
}
}
/// common/exception.ts 实现一个异常捕获
@Catch() // catch装饰器不填参数则捕获所有类型异常,也可以传入错误类型做单独捕获@Catch(HttpException)
export class AllExceptionsFilter implements ExceptionFilter{
catch(exception:unknown,host:ArgumentsHost){
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const request = ctx.getRequest();
let message = '请求发生错误';
let status = HttpStatus.INTERNAL_SERVER_ERROR;
// 对捕获的异常做区分处理
switch (exception.constructor) {
case HttpException:
status = (exception as HttpException).getStatus();
break;
case QueryFailedError:
status = HttpStatus.UNPROCESSABLE_ENTITY;
message = (exception as QueryFailedError).message;
break;
case EntityNotFoundError: // this is another TypeOrm error
status = HttpStatus.UNPROCESSABLE_ENTITY;
message = (exception as EntityNotFoundError).message;
// code = (exception as any).code;
break;
case CannotCreateEntityIdMapError: // and another
status = HttpStatus.UNPROCESSABLE_ENTITY;
message = (exception as CannotCreateEntityIdMapError).message;
break;
case TypeORMError:
status = HttpStatus.UNPROCESSABLE_ENTITY;
message = (exception as TypeORMError).message;
break;
default:
status = HttpStatus.INTERNAL_SERVER_ERROR;
}
response.status(status).json({
status,
message,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}
///main.ts
//使用全局异常捕获,如果有其它类型捕获,应当放在全局异常捕获参数之前
app.useGlobalFilters(/*other exception filters,*/new AllExceptionsFilter());