实体类检验
实体类
首先在实体的属性上添加对应的校验规则,比如 @NotBlank和 @Email注解:
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
@TableName("m_user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@NotBlank(message = "昵称不能为空")
private String username;
@NotBlank(message = "邮箱不能为空")
@Email(message = "邮箱格式不正确")
private String email;
...
}
Controller类
这里我们使用@Validated注解方式,如果实体不符合要求,系统会抛出异常,那么我们的异常处理中就捕获到MethodArgumentNotValidException。
/**
* 测试实体校验
* @param user
* @return
*/
@PostMapping("/save")
public Object testUser(@Validated @RequestBody User user) {
return user.toString();
}
全局异常处理
/**
* 全局异常处理
*/
@Slf4j
@RestControllerAdvice
public class GlobalExcepitonHandler {
// 捕捉shiro的异常
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler(ShiroException.class)
public Result handle401(ShiroException e) {
return Result.fail(401, e.getMessage(), null);
}
/**
* 处理Assert的异常
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = IllegalArgumentException.class)
public Result handler(IllegalArgumentException e) throws IOException {
log.error("Assert异常:-------------->{}",e.getMessage());
return Result.fail(e.getMessage());
}
/**
* @Validated 校验错误异常处理
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public Result handler(MethodArgumentNotValidException e) throws IOException {
log.error("运行时异常:-------------->",e);
BindingResult bindingResult = e.getBindingResult();
ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
return Result.fail(objectError.getDefaultMessage());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = RuntimeException.class)
public Result handler(RuntimeException e) throws IOException {
log.error("运行时异常:-------------->",e);
return Result.fail(e.getMessage());
}
}