当前位置:网站首页>How to use annotations such as @notnull to verify and handle global exceptions
How to use annotations such as @notnull to verify and handle global exceptions
2022-07-03 15:21:00 【You are my forever bug】
@NotNul Wait for the use of annotations
Code : Code cloud
1、 Add dependency
<!-- validation Components -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2、 stay controller Before requesting parameters + @Vaild
@RequestMapping("/doLogin")
@ResponseBody
public RespBean doLogin(@Valid LoginRequestParam param){
}
3、 On the parameter entity class annotations
@Data
public class LoginRequestParam {
@NotBlank(message = "mobile Can't be empty ")
@IsMobile
private String mobile;
@NotBlank(message = "password Can't be empty ")
@Length(min = 32,message = "password The length is not right ")
private String password;
}
here The exception of will not be displayed on the page But will newspaper 400 error , And in Error in background printing , This requires intercepting exceptions
Background error protection information , You know The exception intercepted by the annotation is BindException
Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors<EOL>Field error in object 'loginRequestParam' on field 'mobile': rejected value [11]; codes [IsMobile.loginRequestParam.mobile,IsMobile.mobile,IsMobile.java.lang.String,IsMobile]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [loginRequestParam.mobile,mobile]; arguments []; default message [mobile],true]; default message [ Phone number Format error ]]
Global exception handling
1、 First Definition Abnormal enumeration information
package com.example.seckill.common;
/** * Public return object enumeration * * @author: LC * @date 2022/3/2 1:44 Afternoon * @ClassName: RespBean */
public enum RespBeanEnum {
// Universal
SUCCESS(200, "SUCCESS"),
ERROR(500, " Server exception "),
// Login module
LOGIN_ERROR(500210, " Incorrect username or password "),
MOBILE_ERROR(500211, " Incorrect format of mobile phone number "),
BIND_ERROR(500212, " Parameter verification exception "),
MOBILE_NOT_EXIST(500213, " Mobile number does not exist "),
PASSWORD_UPDATE_FAIL(500214, " Failed to update password "),
SESSION_ERROR(500215, " user SESSION non-existent "),
// Second kill module
EMPTY_STOCK(500500, " Insufficient inventory "),
REPEATE_ERROR(500501, " This product is limited to one per person "),
REQUEST_ILLEGAL(500502, " Illegal request , Please try again "),
ERROR_CAPTCHA(500503, " Verification code error , Please re-enter "),
ACCESS_LIMIT_REACHED(500504, " Too many visits , Please try again later "),
// Order module 5003xx
ORDER_NOT_EXIST(500300, " The order does not exist "),
;
private final Integer code;
private final String message;
public Integer getCode() {
return code;
}
public String getMessage() {
return message;
}
RespBeanEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
}
2、 Definition The format of the returned information
package com.example.seckill.common;
/** * Public return object * * @author: LC * @date 2022/3/2 1:50 Afternoon * @ClassName: RespBean */
public class RespBean {
private long code;
private String message;
private Object object;
public static RespBean success() {
return new RespBean(RespBeanEnum.SUCCESS.getCode(), RespBeanEnum.SUCCESS.getMessage(), null);
}
public static RespBean success(Object object) {
return new RespBean(RespBeanEnum.SUCCESS.getCode(), RespBeanEnum.SUCCESS.getMessage(), object);
}
public static RespBean error(RespBeanEnum respBeanEnum) {
return new RespBean(respBeanEnum.getCode(), respBeanEnum.getMessage(), null);
}
public static RespBean error(RespBeanEnum respBeanEnum, Object object) {
return new RespBean(respBeanEnum.getCode(), respBeanEnum.getMessage(), object);
}
public RespBean(long code, String message, Object object) {
this.code = code;
this.message = message;
this.object = object;
}
public RespBean() {
}
public long getCode() {
return code;
}
public void setCode(long code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
}
3、 Definition Global exception handling class
package com.example.seckill.exception;
import com.example.seckill.common.RespBeanEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/** * * Global exception */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GlobalException extends RuntimeException{
RespBeanEnum respBeanEnum;
}
4、 Definition Exception interceptor
package com.example.seckill.exception;
import com.example.seckill.common.RespBean;
import com.example.seckill.common.RespBeanEnum;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/** * Global exception interceptor * */
@RestControllerAdvice
public class GlobalExceptionHandle {
// Abnormal interception
@ExceptionHandler(Exception.class)
public RespBean ExceptionHandler(Exception e){
if (e instanceof GlobalException){
// If the intercepted exception is our defined exception directly return
GlobalException ex = (GlobalException) e;
return RespBean.error(ex.getRespBeanEnum());
}else if (e instanceof BindException){
// If it is an exception intercepted by annotations Binding exception
BindException e1 = (BindException) e;
RespBean respBean = RespBean.error(RespBeanEnum.BIND_ERROR);
respBean.setMessage(" Abnormal parameter inspection " + e1.getBindingResult().getAllErrors().get(0).getDefaultMessage()); // Show Specific error messages
return respBean;
}
return RespBean.error(RespBeanEnum.ERROR);
}
}
At this point it will be right Intercept exceptions in the code Back to front end , To display ~
边栏推荐
- [cloud native training camp] module VIII kubernetes life cycle management and service discovery
- High quality workplace human beings must use software to recommend, and you certainly don't know the last one
- Summary of JVM knowledge points
- Visual upper system design and development (Halcon WinForm) -4 Communication management
- Basic SQL tutorial
- Global and Chinese market of solder bars 2022-2028: Research Report on technology, participants, trends, market size and share
- The method of parameter estimation of user-defined function in MATLAB
- Global and Chinese markets for indoor HDTV antennas 2022-2028: Research Report on technology, participants, trends, market size and share
- 视觉上位系统设计开发(halcon-winform)-6.节点与宫格
- Kubernetes will show you from beginning to end
猜你喜欢
什么是one-hot encoding?Pytorch中,将label变成one hot编码的两种方式
Kubernetes 进阶训练营 Pod基础
Redis主从、哨兵、集群模式介绍
Visual upper system design and development (Halcon WinForm) -3 Image control
求字符串函数和长度不受限制的字符串函数的详解
Summary of concurrent full knowledge points
Dataframe returns the whole row according to the value
解决pushgateway数据多次推送会覆盖的问题
High quality workplace human beings must use software to recommend, and you certainly don't know the last one
Tensorflow realizes verification code recognition (I)
随机推荐
Mysql报错:[ERROR] mysqld: File ‘./mysql-bin.010228‘ not found (Errcode: 2 “No such file or directory“)
Search in the two-dimensional array of leetcode sword offer (10)
mysql innodb 存储引擎的特性—行锁剖析
Popular understanding of gradient descent
Solve the problem that pushgateway data will be overwritten by multiple push
Apache ant extension tutorial
MySQL reports an error: [error] mysqld: file '/ mysql-bin. 010228‘ not found (Errcode: 2 “No such file or directory“)
Tensorflow realizes verification code recognition (I)
Digital image processing -- popular Canny edge detection
Kubernetes will show you from beginning to end
官网MapReduce实例代码详细批注
SQL server安装位置改不了
阿特拉斯atlas扭矩枪 USB通讯教程基于MTCOM
[probably the most complete in Chinese] pushgateway entry notes
Finally, someone explained the financial risk management clearly
Reentrantlock usage and source code analysis
[daily training] 395 Longest substring with at least k repeated characters
解决pushgateway数据多次推送会覆盖的问题
求字符串函数和长度不受限制的字符串函数的详解
Win10 enterprise 2016 long term service activation tutorial