企业级项目中统一返回值格式和全局异常处理是必须的标配。否则前端要处理十几种不同的返回格式维护成本极高。一、统一返回值DataAccessors(chaintrue)publicclassResultVOT{privateintcode;privateStringmessage;privateTdata;privatelongtimestamp;publicResultVO(){this.timestampSystem.currentTimeMillis();}publicstaticTResultVOTsuccess(Tdata){returnnewResultVOT().setCode(200).setMessage(操作成功).setData(data);}publicstaticTResultVOTerror(intcode,Stringmessage){returnnewResultVOT().setCode(code).setMessage(message);}}二、全局异常处理RestControllerAdvicepublicclassGlobalExceptionHandler{ExceptionHandler(BusinessException.class)publicResultVO?handleBusiness(BusinessExceptione){returnResultVO.error(e.getCode(),e.getMessage());}ExceptionHandler(MethodArgumentNotValidException.class)publicResultVO?handleValidation(MethodArgumentNotValidExceptione){Stringmsge.getBindingResult().getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.joining(; ));returnResultVO.error(400,msg);}ExceptionHandler(Exception.class)publicResultVO?handleOther(Exceptione){returnResultVO.error(500,服务器繁忙);}} 觉得有用的话点赞 关注【张老师技术栈】吧