当前位置:网站首页>如何使用 @NotNull等注解校验 并全局异常处理
如何使用 @NotNull等注解校验 并全局异常处理
2022-07-03 15:18:00 【ジ你是我永远のbugグ】
@NotNul 等注解的使用
代码:码云
1、添加依赖
<!-- validation组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2、在 controller 请求参数前 + @Vaild
@RequestMapping("/doLogin")
@ResponseBody
public RespBean doLogin(@Valid LoginRequestParam param){
}
3、在参数实体类上 加注解
@Data
public class LoginRequestParam {
@NotBlank(message = "mobile不能为空")
@IsMobile
private String mobile;
@NotBlank(message = "password不能为空")
@Length(min = 32,message = "password 长度不对")
private String password;
}
此时 的异常不会在页面显示 而是会 报400错误,并在 后台打印出错误,这就需要对异常进行拦截
后台保错信息,可知 注解拦截的异常为 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 [手机号码 格式错误]]
全局异常处理
1、 首先 定义 异常的枚举信息
package com.example.seckill.common;
/** * 公共返回对象枚举 * * @author: LC * @date 2022/3/2 1:44 下午 * @ClassName: RespBean */
public enum RespBeanEnum {
//通用
SUCCESS(200, "SUCCESS"),
ERROR(500, "服务端异常"),
//登录模块
LOGIN_ERROR(500210, "用户名或者密码不正确"),
MOBILE_ERROR(500211, "手机号码格式不正确"),
BIND_ERROR(500212, "参数校验异常"),
MOBILE_NOT_EXIST(500213, "手机号码不存在"),
PASSWORD_UPDATE_FAIL(500214, "更新密码失败"),
SESSION_ERROR(500215, "用户SESSION不存在"),
//秒杀模块
EMPTY_STOCK(500500, "库存不足"),
REPEATE_ERROR(500501, "该商品每人限购一件"),
REQUEST_ILLEGAL(500502, "请求非法,请重新尝试"),
ERROR_CAPTCHA(500503, "验证码错误,请重新输入"),
ACCESS_LIMIT_REACHED(500504, "访问过于频繁,请稍后重试"),
//订单模块5003xx
ORDER_NOT_EXIST(500300, "订单不存在"),
;
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、 定义 返回信息的格式
package com.example.seckill.common;
/** * 公共返回对象 * * @author: LC * @date 2022/3/2 1:50 下午 * @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、 定义 全局异常处理类
package com.example.seckill.exception;
import com.example.seckill.common.RespBeanEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/** * * 全局异常 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GlobalException extends RuntimeException{
RespBeanEnum respBeanEnum;
}
4、 定义 异常拦截器
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;
/** * 全局异常拦截器 * */
@RestControllerAdvice
public class GlobalExceptionHandle {
// 异常拦截
@ExceptionHandler(Exception.class)
public RespBean ExceptionHandler(Exception e){
if (e instanceof GlobalException){
// 如果拦截的异常是我们定义的异常 则直接return
GlobalException ex = (GlobalException) e;
return RespBean.error(ex.getRespBeanEnum());
}else if (e instanceof BindException){
// 如果是注解拦截的异常 绑定异常
BindException e1 = (BindException) e;
RespBean respBean = RespBean.error(RespBeanEnum.BIND_ERROR);
respBean.setMessage("参数检验异常" + e1.getBindingResult().getAllErrors().get(0).getDefaultMessage()); //显示 具体错误信息
return respBean;
}
return RespBean.error(RespBeanEnum.ERROR);
}
}
此时就会对 代码中的异常进行拦截 返回到前端,进行展示~
边栏推荐
- . Net six design principles personal vernacular understanding, please correct if there is any error
- 官网MapReduce实例代码详细批注
- [Yu Yue education] scientific computing and MATLAB language reference materials of Central South University
- Functional modules and application scenarios covered by the productization of user portraits
- 【Transformer】入门篇-哈佛Harvard NLP的原作者在2018年初以逐行实现的形式呈现了论文The Annotated Transformer
- [cloud native training camp] module VIII kubernetes life cycle management and service discovery
- Center and drag linked global and Chinese markets 2022-2028: Research Report on technology, participants, trends, market size and share
- Chapter 04_ Logical architecture
- Remote server background hangs nohup
- Global and Chinese market of postal automation systems 2022-2028: Research Report on technology, participants, trends, market size and share
猜你喜欢
Unity hierarchical bounding box AABB tree
Basic SQL tutorial
Functional modules and application scenarios covered by the productization of user portraits
Didi off the shelf! Data security is national security
【云原生训练营】模块八 Kubernetes 生命周期管理和服务发现
Influxdb2 sources add data sources
高并发下之redis锁优化实战
Concurrency-02-visibility, atomicity, orderliness, volatile, CAS, atomic class, unsafe
Jvm-02-class loading subsystem
Leasing cases of the implementation of the new regulations on the rental of jointly owned houses in Beijing
随机推荐
Global and Chinese markets of AC electromechanical relays 2022-2028: Research Report on technology, participants, trends, market size and share
阿特拉斯atlas扭矩枪 USB通讯教程基于MTCOM
Global and Chinese market of trimethylamine 2022-2028: Research Report on technology, participants, trends, market size and share
Leetcode sword offer find the number I (nine) in the sorted array
Relationship between truncated random distribution and original distribution
求字符串函数和长度不受限制的字符串函数的详解
Can‘t connect to MySQL server on ‘localhost‘
【Transform】【实践】使用Pytorch的torch.nn.MultiheadAttention来实现self-attention
GCC cannot find the library file after specifying the link library path
基础SQL教程
Final review points of human-computer interaction
Characteristics of MySQL InnoDB storage engine -- Analysis of row lock
Detailed comments on MapReduce instance code on the official website
[transform] [practice] use pytoch's torch nn. Multiheadattention to realize self attention
Global and Chinese market of lighting control components 2022-2028: Research Report on technology, participants, trends, market size and share
Kubernetes vous emmène du début à la fin
MySQL reports an error: [error] mysqld: file '/ mysql-bin. 010228‘ not found (Errcode: 2 “No such file or directory“)
Yolov5系列(一)——网络可视化工具netron
Explanation of time complexity and space complexity
Puppet automatic operation and maintenance troubleshooting cases