当前位置:网站首页>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 ~
边栏推荐
- [pytorch learning notes] datasets and dataloaders
- 【可能是全中文网最全】pushgateway入门笔记
- [transformer] Introduction - the original author of Harvard NLP presented the annotated transformer in the form of line by line implementation in early 2018
- Global and Chinese market of transfer case 2022-2028: Research Report on technology, participants, trends, market size and share
- What are the composite types of Blackhorse Clickhouse, an OLAP database recognized in the industry
- 什么是embedding(把物体编码为一个低维稠密向量),pytorch中nn.Embedding原理及使用
- Redis lock Optimization Practice issued by gaobingfa
- Explanation of time complexity and space complexity
- Jvm-09 byte code introduction
- Visual host system design and development (Halcon WinForm)
猜你喜欢
![[cloud native training camp] module 7 kubernetes control plane component: scheduler and controller](/img/a4/2156b61fbf50db65fdf59c8f5538f8.png)
[cloud native training camp] module 7 kubernetes control plane component: scheduler and controller

Chapter 04_ Logical architecture

The markdown file obtains the pictures of the network and stores them locally and modifies the URL

Halcon与Winform学习第一节

Jvm-08-garbage collector

el-switch 赋值后状态不变化

Characteristics of MySQL InnoDB storage engine -- Analysis of row lock

【Transform】【NLP】首次提出Transformer,Google Brain团队2017年论文《Attention is all you need》

运维体系的构建
![MySQL reports an error: [error] mysqld: file '/ mysql-bin. 010228‘ not found (Errcode: 2 “No such file or directory“)](/img/cd/2e4f5884d034ff704809f476bda288.png)
MySQL reports an error: [error] mysqld: file '/ mysql-bin. 010228‘ not found (Errcode: 2 “No such file or directory“)
随机推荐
Kubernetes vous emmène du début à la fin
"Seven weapons" in the "treasure chest" of machine learning: Zhou Zhihua leads the publication of the new book "machine learning theory guide"
详解指针进阶1
Halcon与Winform学习第二节
如何使用 @NotNull等注解校验 并全局异常处理
秒杀系统2-Redis解决分布式Session问题
Apache ant extension tutorial
leetcode_ Power of Four
Global and Chinese markets for flexible chips 2022-2028: Research Report on technology, participants, trends, market size and share
自定义注解
Besides lying flat, what else can a 27 year old do in life?
Global and Chinese market of solder bars 2022-2028: Research Report on technology, participants, trends, market size and share
[attention mechanism] [first vit] Detr, end to end object detection with transformers the main components of the network are CNN and transformer
Finally, someone explained the financial risk management clearly
使用JMeter对WebService进行压力测试
视觉上位系统设计开发(halcon-winform)-4.通信管理
Redis single thread problem forced sorting layman literacy
The method of parameter estimation of user-defined function in MATLAB
What is machine reading comprehension? What are the applications? Finally someone made it clear
Jvm-04-runtime data area heap, method area