當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring Boot笔记-validation的使用及统一异常处理
生活随笔
收集整理的這篇文章主要介紹了
Spring Boot笔记-validation的使用及统一异常处理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這里以JPA后端分頁為例,演示下validation的使用,及統一異常處理。
正常分頁查詢:
page頁是從0開始的,我這里返回的時候,給他加1了。這里要注意。
當出現異常的查詢時:
及
這里的關鍵異常處理是這個類:
/**** 統一異常處理、數據預處理*/ @ControllerAdvice public class ControllerExceptionHandler {@ExceptionHandler(value = BindException.class)@ResponseBodypublic CommonResp validExceptionHandler(BindException e){CommonResp commonResp = new CommonResp();commonResp.setSuccess(false);e.printStackTrace();commonResp.setMessage(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());return commonResp;} }其中BindException就是validation的異常
對應的validation設置的類為:
package cn.it1995.req;import lombok.Data;import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull;@Data public class PageRequest {@NotNull(message = "頁碼不能為空")@Min(value = 0, message = "頁碼不能為負")private Integer page;@NotNull(message = "每頁條數不能為空")@Min(value = 1, message = "每頁條數至少為1條")@Max(value = 1000, message = "每頁條數不能超過1000")private Integer size; }要使用validation需要在maven中添加:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId> </dependency>源碼打包下載地址:
https://github.com/fengfanchen/Java/tree/master/JPAPageable
?
總結
以上是生活随笔為你收集整理的Spring Boot笔记-validation的使用及统一异常处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt笔记-profile中基本配置(获取
- 下一篇: Qt笔记-QSslSocket双向认证