日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringBoot/Cloud 统一返回优雅设计+自定义异常

發(fā)布時(shí)間:2024/9/27 javascript 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot/Cloud 统一返回优雅设计+自定义异常 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.


文章目錄

            • 1. 返回結(jié)果封裝
            • 2. 自定義異常
            • 3. 校驗(yàn)工具類
            • 4. 使用案例
            • 5. 前端效果圖

1. 返回結(jié)果封裝
package com.course.server.dto;public class ResponseDto<T> {/*** 業(yè)務(wù)上的成功或失敗*/private boolean success = true;/*** 返回碼*/private String code;/*** 返回信息*/private String message;/*** 返回泛型數(shù)據(jù),自定義類型*/private T content;public String getCode() {return code;}public void setCode(String code) {this.code = code;}public boolean getSuccess() {return success;}public void setSuccess(boolean success) {this.success = success;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}public T getContent() {return content;}public void setContent(T content) {this.content = content;}@Overridepublic String toString() {final StringBuffer sb = new StringBuffer("ResponseDto{");sb.append("success=").append(success);sb.append(", code='").append(code).append('\'');sb.append(", message='").append(message).append('\'');sb.append(", content=").append(content);sb.append('}');return sb.toString();} }
2. 自定義異常
package com.course.server.exception;public class ValidatorException extends RuntimeException {public ValidatorException(String message) {super(message);} }
3. 校驗(yàn)工具類
package com.course.server.util;import com.course.server.exception.ValidatorException; import org.springframework.util.StringUtils;public class ValidatorUtil {/*** 空校驗(yàn)(null or "")*/public static void require(Object str, String fieldName) {if (StringUtils.isEmpty(str)) {throw new ValidatorException(fieldName + "不能為空");}}/*** 長度校驗(yàn)*/public static void length(String str, String fieldName, int min, int max) {if (StringUtils.isEmpty(str)) {return;}int length = 0;if (!StringUtils.isEmpty(str)) {length = str.length();}if (length < min || length > max) {throw new ValidatorException(fieldName + "長度" + min + "~" + max + "位");}}}
4. 使用案例
@PostMapping("/save")public ResponseDto save(@RequestBody ChapterDto chapterDto) {// 保存校驗(yàn)ValidatorUtil.require(chapterDto.getName(), "名稱");ValidatorUtil.require(chapterDto.getCourseId(), "課程ID");ValidatorUtil.length(chapterDto.getCourseId(), "課程ID", 1, 8);ResponseDto responseDto = new ResponseDto();chapterService.save(chapterDto);responseDto.setContent(chapterDto);return responseDto;}
5. 前端效果圖


總結(jié)

以上是生活随笔為你收集整理的SpringBoot/Cloud 统一返回优雅设计+自定义异常的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。