當(dāng)前位置:
首頁(yè) >
前端技术
> javascript
>内容正文
javascript
SpringBoot/Cloud 统一返回优雅设计+自定义异常
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot/Cloud 统一返回优雅设计+自定义异常
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- 1. 返回結(jié)果封裝
- 2. 自定義異常
- 3. 校驗(yàn)工具類(lèi)
- 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ù),自定義類(lèi)型*/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)工具類(lèi)
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 + "不能為空");}}/*** 長(zhǎng)度校驗(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 + "長(zhǎng)度" + min + "~" + max + "位");}}}4. 使用案例
@PostMapping("/save")public ResponseDto save(@RequestBody ChapterDto chapterDto) {// 保存校驗(yàn)ValidatorUtil.require(chapterDto.getName(), "名稱(chēng)");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 统一返回优雅设计+自定义异常的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: DockerFile 入门到精通
- 下一篇: 企业微信小程序_小程序开发工具及真机调试