在nestjs中处理typeorm异常

在业务处理中发生错误,在官网的示例中没有具体的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());
  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值