springboot进阶
表单验证
- @Valid 验证注解
- BindingResult 返回结果
- bindingResult.getFieldError().getDefaultMessage() 获取错误信息
public void create(@Valid Luckymoney luckymoney, BindingResult bindingResult){
if (bindingResult.hasErrors()) {
// bindingResult.getFieldError().getDefaultMessage()
}
}
AOP处理请求
- 类注解: @Aspect @Component
- 切点: @Pointcut
- 调用之前:@Before
- 调用之后:@After
输出日志
- 所属包:org.slf4j.Logger
- 在哪个类打印日志:HttpAspect.class
- 打印日志方法
- logger.info()
- logger.error();
- logger.debug();
- logger.warn();
private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);
指定切点
- 括号中填写路径
- *代表所有方法,也可以指定某个方法
- … 代表任何参数都会被拦截
@Pointcut("execution(public * com.lxh.summer.controller.LuckymoneyController.*(..))")
public void log(){
}
调用之前及调用之后
- log()指定切点
@Before("log()")
public void doBefore(JoinPoint joinPoint) {
logger.info("before");
}
@After("log()")
public void doAfter() {
logger.info("after");
}
返回结果
- returning返回结果,pointcut切点
@AfterReturning(returning = "object", pointcut = "log()")
public void doAfterReturning(Object object) {
logger.info("response={}", object);
}
记录http请求
// 记录http请求
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//url
logger.info("url={}", request.getRequestURL());
//method
logger.info("method={}", request.getMethod());
// ip
logger.info("ip={}", request.getRemoteAddr());
//类方法
logger.info("classMethod={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
// 参数
logger.info("args={}", joinPoint.getArgs());
统一异常处理
流程
- 定义返回数据格式
- 定义统一数据处理
- 捕获异常
- 自定义异常
- 异常枚举定义
具体操作
定义数据格式
public class Result<T> {
/* 错误码*/
private Integer code;
/* 信息*/
private String msg;
/* 数据*/
private T data;
// getter setter 略
}
定义统一数据处理
public class ResultUtil {
public static Result success(Object object) {
Result result = new Result();
result.setCode(ResultEnum.SUCCESS.getCode());
result.setMsg(ResultEnum.SUCCESS.getMessage());
result.setData(object);
return result;
}
public static Result success() {
return success(null);
}
public static Result error(Integer code, String msg) {
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
return result;
}
}
捕获异常
- 类注解:@ControllerAdvice
- 方法注解:
- @ExceptionHandler(value = Exception.class) 指定捕获哪个类的异常
- @ResponseBody 返回json格式
- 是否是自定义异常: e instanceof LuckymoneyException
@ControllerAdvice
public class ExceptionHandle {
private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handle(Exception e) {
if (e instanceof LuckymoneyException) {
LuckymoneyException luckymoneyException = (LuckymoneyException) e;
return ResultUtil.error(luckymoneyException.getCode(), luckymoneyException.getMessage());
}
logger.error("系统错误", e);
return ResultUtil.error(ResultEnum.UNKNOWN_ERROR.getCode(), ResultEnum.UNKNOWN_ERROR.getMessage());
}
}
自定义异常
- RuntimeException:必须继承运行时异常,否则框架处理不了
public class LuckymoneyException extends RuntimeException {
private Integer code;
public LuckymoneyException(ResultEnum resultEnum) {
super(resultEnum.getMessage());
this.code = resultEnum.getCode();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
异常枚举定义
public enum ResultEnum {
UNKNOWN_ERROR(-500, "未知错误"),
SMALL_LUCKY(0, "红包太小了"),
BIG_LUCKY(1, "红包太大了"),
SUCCESS(200, "成功"),
FAILURE(400, "失败")
;
private Integer code;
private String message;
ResultEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer getCode() {
return code;
}
public String getMessage() {
return message;
}
}
示例
service层
public Luckymoney getMoney(Integer id) throws Exception{
Luckymoney luckymoney = respository.findById(id).orElse(null);
BigDecimal money = luckymoney.getMoney();
if (money.compareTo(new BigDecimal(100)) < 0){
// 抛出自定义异常
throw new LuckymoneyException(ResultEnum.SMALL_LUCKY);
} else if (money.compareTo(new BigDecimal(100)) > 0) {
throw new LuckymoneyException(ResultEnum.BIG_LUCKY);
} else {
return luckymoney;
}
}
controller层
@GetMapping("/luckymoney/{id}")
public Result getMoneyById(@PathVariable("id") Integer id) throws Exception{
// 返回统一结果
return ResultUtil.success(servive.getMoney(id));
}
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦