当前位置: 首页 > 后端技术 > Node.js

Malagu统一响应格式和自定义异常

时间:2023-04-03 22:56:04 Node.js

介绍活动链接:https://github.com/weopenproj...不管是restfull风格的API还是其他的,统一的响应格式是必不可少的。响应格式的一致性使得接口规范统一,接口也易于维护。本文将举例说明malagu统一响应格式的实践,包括自定义异常的实现。项目结构红框文件:统一响应格式和自定义异常文件统一响应格式实现1.定义ResponseData接口,文件:response-data.tsexportinterfaceResponseData{code:1|数字,数据:T|null,message:string}2.定义响应结果格式化函数responseJson,文件:format-util.ts/*格式化工具*@Author:pwzhang*@Date:2022-08-1817:03:40*@LastModifiedby:pwzhang*@LastModifiedtime:2022-08-1817:17:53*/import{ResponseData}from"../../common/data/response-data";/***接口响应格式*@paramdata[any]returnbody*@paramerror[错误|string]错误信息|错误描述*@returns{*code,0-失败;1-success*data,*messageerrordescription*}*/exportconstresponseJson=(data:T,error:any=null):ResponseData=>{letcode:0|}1=错误?1:0;让消息:字符串=错误?(error.message||error):'';return{code,data,message};}3.在controller中应用responseJson函数@Get("/:userId")@Json()@Authenticated()asyncgetUserInfo(@Param("userId")userId:number){this.logger.info(`获取用户信息:${userId}`)constresult=awaitthis.userInfoService.getUserInfo(userId);returnresponseJson(result)}Responseresult:至此,成功响应的统一格式完成,再结合自定义异常的实现1.自定义异常类WebCunstomError,文件:web-cunstom-error.tsimport{CustomError}from"@malagu/core";/**@Author:pwzhang*@Date:2022-08-0718:51:21*@LastModifiedby:pwzhang*@LastModifiedtime:2022-08-1914:56:01*/exportclassWebCunstomErrorextendsCustomError{constructor(publicmessage:string="unknownException"){super(message);}}2。自定义异常处理程序WebCustomErrorHandler,文件:web-custom-error-hander.tsimport{Autowired,Component,Logger}from"@malagu/core";import{Context,ErrorHandler,HTTP_ERROR_HANDLER_PRIORITY,}from"@malagu/web/lib/node“;从“../../node/utils/format-util”导入{responseJson};从“../error/web-custom-error”导入{WebCunstomError};/**@作者:pwzhang*@日期:2022-08-0718:24:19*@LastModifiedby:pwzhang*@LastModifiedtime:2022-08-1915:59:55*/@Component([WebCustomErrorHandler,ErrorHandler])exportclassWebCustomErrorHandlerimplementsErrorHandler{readonlypriority:number=HTTP_ERROR_HANDLYER;_PRIITRY(Logger)受保护的记录器:记录器;canHandle(ctx:Context,err:Error):Promise{返回Promise。resolve(errinstanceofWebCunstomError)}asynchandle(ctx:Context,err:WebCunstomError):Promise{//结束线程ctx.response.end(JSON.stringify(responseJson(null,err)));}}3.服务或控制器文件中的应用程序自定义异常}错误响应结果结语思路使用trycatch捕获异常后,日志没有输出异常信息指正!思考内容欢迎大家回答问题

最新推荐
猜你喜欢