博客
关于我
AOP加全局异常返回给前端信息
阅读量:513 次
发布时间:2019-03-07

本文共 1642 字,大约阅读时间需要 5 分钟。

定义一个异常类:

/** * 异常 */public class CheckException extends Exception {    public CheckException(String message) {        super(message);    }}

定义一个aop(注解形式使用)

定义注解:

为什么这么定义的解释:

@Target({ElementType.METHOD, ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface CheckUrl {}

定义aop,这是一个判断传参是否为空的aop:

@Component@Aspectpublic class UrlCheckAspect {    //定义的注解的位置    @Before("@annotation(com.config.aop.CheckUrl)")    public void doInputCheckBefore(JoinPoint joinPoint) throws Throwable {        Object[] paramValues = joinPoint.getArgs();        String[] paramNames = ((CodeSignature)joinPoint.getSignature()).getParameterNames();        StrBuilder strBuilder = new StrBuilder();        for (int i = 0; i < paramNames.length; i++) {            if(paramValues[i] == null){                strBuilder.append(paramNames[i]).append("必传  ");            }        }        if (StringUtils.isNotEmpty(strBuilder.toString())) {            throw new CheckException(strBuilder.toString());        }    }}

定义全局异常:

@ControllerAdvicepublic class GlobalExceptionConfig {    @ResponseBody    @ExceptionHandler(CheckException.class)    //HttpResponse:格式化返回值的一个util    public HttpResponse
checkUrlException(CheckException e) { return HttpResponse.fail(e.getMessage()); }}

使用方式:

判断前端传过来的userId是否为空,必须加“required = false”,如果不加会被框架打回,得不到我们想要的结果

//判断前端传过来的userId是否为空    @CheckUrl    @GetMapping("/get_by_id")    public HttpResponse
getUserById(@RequestParam(required = false) Long userId) { User byId = userService.getById(userId); return byId == null ? HttpResponse.fail("用户不存在") : HttpResponse.success(byId); }

 

转载地址:http://crmjz.baihongyu.com/

你可能感兴趣的文章
multivariate_normal TypeError: ufunc ‘add‘ output (typecode ‘O‘) could not be coerced to provided……
查看>>
MySQL DBA 数据库优化策略
查看>>
multi_index_container
查看>>
mutiplemap 总结
查看>>
MySQL Error Handling in Stored Procedures---转载
查看>>
MVC 区域功能
查看>>
MySQL FEDERATED 提示
查看>>
mysql generic安装_MySQL 5.6 Generic Binary安装与配置_MySQL
查看>>
Mysql group by
查看>>
MySQL I 有福啦,窗口函数大大提高了取数的效率!
查看>>
mysql id自动增长 初始值 Mysql重置auto_increment初始值
查看>>
MySQL in 太多过慢的 3 种解决方案
查看>>
Mysql Innodb 锁机制
查看>>
MySQL InnoDB中意向锁的作用及原理探
查看>>
MySQL InnoDB事务隔离级别与锁机制深入解析
查看>>
Mysql InnoDB存储引擎 —— 数据页
查看>>
Mysql InnoDB存储引擎中的checkpoint技术
查看>>
Mysql InnoDB存储引擎中缓冲池Buffer Pool、Redo Log、Bin Log、Undo Log、Channge Buffer
查看>>
MySQL InnoDB引擎的锁机制详解
查看>>
Mysql INNODB引擎行锁的3种算法 Record Lock Next-Key Lock Grap Lock
查看>>