Vue3 + Nest 实现博客管理系统 后端篇(三):异常处理和格式化返回数据

Vue3 + Nest 实现博客管理系统 后端篇(二):用户表设计及登录注册功能实现 已经实现了登录注册的功能,同时也发现了对于异常返回的信息比较乱,还有返回的数据没有做统一的处理,本章节将会对这两个做一个处理

首先我们创建一个异常过滤器在libs/filters/http-exception.filter.ts

Vue3 + Nest 实现博客管理系统 后端篇(三):异常处理和格式化返回数据

import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    const message = exception.message;

    Logger.log('错误提示', message);
    const errorResponse = {
      code: status,
      message,
      url: request.originalUrl,
      timestamp: new Date().toISOString(),
    };

    // 设置返回的状态码、请求头、发送错误信息
    response.status(status).json(errorResponse);
  }
}

在main.ts挂载为全局过滤器

Vue3 + Nest 实现博客管理系统 后端篇(三):异常处理和格式化返回数据

我们继续使用查询接口进行测试

Vue3 + Nest 实现博客管理系统 后端篇(三):异常处理和格式化返回数据

Vue3 + Nest 实现博客管理系统 后端篇(三):异常处理和格式化返回数据

格式化返回数据

在开发过程中我们需要后端返回的数据接口一般为:

{
    data: 返回数据,
    code: 状态码,
    message: 描述信息
    ...
}

首先我们在libs/filters/apiresult.format.ts 封装一下我们需要的结构

Vue3 + Nest 实现博客管理系统 后端篇(三):异常处理和格式化返回数据

import { Injectable } from '@nestjs/common';

@Injectable()
export class ApiresultService {
  MESSAGE(code: number, message: string, data?: any) {
    return {
      code,
      message,
      data,
    };
  }
}

ApiresultService 类里面的MESSAGE接收至少两个参数(code, message)

code:状态码,message:描述信息,data:业务数据

然后我们继续在findAll 接口去测试,修改user.service.ts

Vue3 + Nest 实现博客管理系统 后端篇(三):异常处理和格式化返回数据

Vue3 + Nest 实现博客管理系统 后端篇(三):异常处理和格式化返回数据

  async findAll() {
    try {
      const data = await this.userRepository.find();
      return {
        ...this.Apiresult.MESSAGE(200, '查询成功', data),
      };
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

在apifox 查询数据

Vue3 + Nest 实现博客管理系统 后端篇(三):异常处理和格式化返回数据
数据格式化和异常处理就到这了,这个格式化目前是这么处理,肯定有更好的方式,以后可能还会再次更新修改,工作最开心的时刻除了发工资,节假日,就是周五了,哎嘿,今天周五!!!

原文链接:https://juejin.cn/post/7265937125001183266 作者:大彭

(0)
上一篇 2023年8月12日 上午10:41
下一篇 2023年8月12日 上午10:51

相关推荐

发表回复

登录后才能评论