当前位置:网站首页>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 ~
边栏推荐
- 秒杀系统1-登录功能
- 使用JMeter对WebService进行压力测试
- 整形和浮点型是如何在内存中的存储
- Markdown file titles are all reduced by one level
- Puppet自动化运维排错案例
- Kubernetes带你从头到尾捋一遍
- Global and Chinese market of air cargo logistics 2022-2028: Research Report on technology, participants, trends, market size and share
- Use of Tex editor
- Influxdb2 sources add data sources
- Dataframe returns the whole row according to the value
猜你喜欢

Popular understanding of decision tree ID3

Redis lock Optimization Practice issued by gaobingfa

从 flask 服务端代码自动生成客户端代码 -- flask-native-stubs 库介绍

Kubernetes帶你從頭到尾捋一遍

Digital image processing -- popular Canny edge detection

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)

Didi off the shelf! Data security is national security

视觉上位系统设计开发(halcon-winform)-3.图像控件

GCC cannot find the library file after specifying the link library path
随机推荐
[pytorch learning notes] transforms
The first character of leetcode sword offer that only appears once (12)
Leasing cases of the implementation of the new regulations on the rental of jointly owned houses in Beijing
Didi off the shelf! Data security is national security
C语言刷题~Leetcode与牛客网简单题
Use of Tex editor
Kubernetes advanced training camp pod Foundation
Visual upper system design and development (Halcon WinForm) -4 Communication management
开启 Chrome 和 Edge 浏览器多线程下载
Kubernetes will show you from beginning to end
[pytorch learning notes] datasets and dataloaders
Jvm-04-runtime data area heap, method area
Global and Chinese market of air cargo logistics 2022-2028: Research Report on technology, participants, trends, market size and share
高并发下之redis锁优化实战
redis缓存穿透,缓存击穿,缓存雪崩解决方案
【云原生训练营】模块八 Kubernetes 生命周期管理和服务发现
Enable multi-threaded download of chrome and edge browsers
秒杀系统1-登录功能
Unity hierarchical bounding box AABB tree
Nppexec get process return code