当前位置:网站首页>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 ~
边栏推荐
- leetcode_ Power of Four
- 基础SQL教程
- [probably the most complete in Chinese] pushgateway entry notes
- Jvm-08-garbage collector
- Baidu AI Cloud helps Shizuishan upgrade the smart health care model of "Internet + elderly care services"
- Global and Chinese market of Bus HVAC systems 2022-2028: Research Report on technology, participants, trends, market size and share
- Global and Chinese markets for flexible chips 2022-2028: Research Report on technology, participants, trends, market size and share
- Kubernetes帶你從頭到尾捋一遍
- [combinatorics] permutation and combination (set permutation, step-by-step processing example)
- Can‘t connect to MySQL server on ‘localhost‘
猜你喜欢

秒杀系统1-登录功能

Introduction to redis master-slave, sentinel and cluster mode

如何使用 @NotNull等注解校验 并全局异常处理

【云原生训练营】模块七 Kubernetes 控制平面组件:调度器与控制器

Halcon与Winform学习第二节

High quality workplace human beings must use software to recommend, and you certainly don't know the last one

Redis cache penetration, cache breakdown, cache avalanche solution

Kubernetes帶你從頭到尾捋一遍

Reentrantlock usage and source code analysis

Kubernetes vous emmène du début à la fin
随机推荐
Redis lock Optimization Practice issued by gaobingfa
详解指针进阶1
视觉上位系统设计开发(halcon-winform)-2.全局变量设计
阿特拉斯atlas扭矩枪 USB通讯教程基于MTCOM
Final review points of human-computer interaction
Redis主从、哨兵、集群模式介绍
SQL server installation location cannot be changed
Jvm-03-runtime data area PC, stack, local method stack
[cloud native training camp] module 7 kubernetes control plane component: scheduler and controller
XWiki Installation Tips
Idea does not specify an output path for the module
Visual host system design and development (Halcon WinForm)
What is one hot encoding? In pytoch, there are two ways to turn label into one hot coding
Detailed comments on MapReduce instance code on the official website
What is embedding (encoding an object into a low dimensional dense vector), NN in pytorch Principle and application of embedding
Introduction, use and principle of synchronized
Calibre LVL
Popular understanding of ovo and ovr
Summary of concurrent full knowledge points
Jvm-08-garbage collector