当前位置:网站首页>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 ~
边栏推荐
- Finally, someone explained the financial risk management clearly
- Using multipleoutputs to output multiple files in MapReduce
- Characteristics of MySQL InnoDB storage engine -- Analysis of row lock
- [daily training] 395 Longest substring with at least k repeated characters
- Using TCL (tool command language) to manage Tornado (for VxWorks) can start the project
- Kubernetes 进阶训练营 Pod基础
- Markdown file titles are all reduced by one level
- 视觉上位系统设计开发(halcon-winform)-2.全局变量设计
- Popular understanding of gradient descent
- Jvm-02-class loading subsystem
猜你喜欢
Visual upper system design and development (Halcon WinForm) -5 camera
Jvm-06-execution engine
[probably the most complete in Chinese] pushgateway entry notes
Visual host system design and development (Halcon WinForm)
Jvm-08-garbage collector
What are the composite types of Blackhorse Clickhouse, an OLAP database recognized in the industry
C语言刷题~Leetcode与牛客网简单题
Visual upper system design and development (Halcon WinForm) -4 Communication management
What is machine reading comprehension? What are the applications? Finally someone made it clear
[cloud native training camp] module VIII kubernetes life cycle management and service discovery
随机推荐
Idea does not specify an output path for the module
Halcon与Winform学习第一节
视觉上位系统设计开发(halcon-winform)-4.通信管理
【Transformer】入门篇-哈佛Harvard NLP的原作者在2018年初以逐行实现的形式呈现了论文The Annotated Transformer
Jvm-08-garbage collector
Redis lock Optimization Practice issued by gaobingfa
App全局异常捕获
Apache ant extension tutorial
Atlas atlas torque gun USB communication tutorial based on mtcom
Visual upper system design and development (Halcon WinForm) -6 Nodes and grids
High quality workplace human beings must use software to recommend, and you certainly don't know the last one
[transform] [practice] use pytoch's torch nn. Multiheadattention to realize self attention
Introduction to redis master-slave, sentinel and cluster mode
C语言刷题~Leetcode与牛客网简单题
秒杀系统3-商品列表和商品详情
运维体系的构建
Using TCL (tool command language) to manage Tornado (for VxWorks) can start the project
Global and Chinese market of air cargo logistics 2022-2028: Research Report on technology, participants, trends, market size and share
[cloud native training camp] module VIII kubernetes life cycle management and service discovery
Kubernetes will show you from beginning to end