通常在开发具体项目过程中我们可能会面临如下问题:

  1. 统一所有的json返回结果
  2. 统一处理所有controller中的异常,并且给不同异常不同的返回状态值
  3. 统一对返回的接口做数据校验或者加密,防止篡改

在spring中的处理方式是使用@RestControllerAdvice注解。下面是一个例子,可以将所有的controller中的返回结果,包装成一个CommonResponse。

@RestControllerAdvice
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> { @Override
@SuppressWarnings("all")
public boolean supports(MethodParameter methodParameter,
Class<? extends HttpMessageConverter<?>> aClass) { if (methodParameter.getDeclaringClass().isAnnotationPresent(
IgnoreResponseAdvice.class
)) {
return false;
} if (methodParameter.getMethod().isAnnotationPresent(
IgnoreResponseAdvice.class
)) {
return false;
} return true;
} @Nullable
@Override
@SuppressWarnings("all")
public Object beforeBodyWrite(@Nullable Object o,
MethodParameter methodParameter,
MediaType mediaType,
Class<? extends HttpMessageConverter<?>> aClass,
ServerHttpRequest serverHttpRequest,
ServerHttpResponse serverHttpResponse) { CommonResponse<Object> response = new CommonResponse<>(0, "");
if (null == o) {
return response;
} else if (o instanceof CommonResponse) {
response = (CommonResponse<Object>) o;
} else {
response.setData(o);
} return response;
}
}

  上述代码中定义了一个注解IgnoreResponseAdvice,如果controller的类或者方法有这个注解就不做处理。下面这个例子展现的是如何在controller抛出异常的时候,自动包装成为commonRespons。

@RestControllerAdvice
public class GlobalExceptionAdvice { @ExceptionHandler(value = ParamException.class)
public CommonResponse<String> handlerParamException(HttpServletRequest req,
ParamException ex) {
CommonResponse<String> response = new CommonResponse<>(400,
"param error");
response.setData(ex.getMessage());
return response;
}
@ExceptionHandler(value = BusinessException.class)
public CommonResponse<String> handlerBusinessException(HttpServletRequest req,
BusinessException ex) {
CommonResponse<String> response = new CommonResponse<>(500,
"business error");
response.setData(ex.getMessage());
return response;
} @ExceptionHandler(value = SystemException.class)
public CommonResponse<String> handlerSystemException(HttpServletRequest req,
SystemException ex) {
CommonResponse<String> response = new CommonResponse<>(700,
"system error");
response.setData(ex.getMessage());
return response;
}
}

  对比下面的controller能更清楚的明白如何使用。

@RestController
public class IndexController { @RequestMapping("/")
String home() {
return "Hello World!";
}
@IgnoreResponseAdvice
@RequestMapping("/hi")
String hi() {
return "Hello World!";
} @RequestMapping("/param")
String param() throws Exception {
throw new ParamException("参数错误");
} @RequestMapping("/business")
String business() throws Exception {
throw new BusinessException("业务错误");
}
@RequestMapping("/system")
String system() throws Exception {
throw new SystemException("系统错误");
}
}

  详细的代码见 https://gitee.com/dongqihust/arst/tree/master/custom-response

  特别的,这个文章提供了几种其他的解决方案:https://www.baeldung.com/exception-handling-for-rest-with-spring

ARTS打卡计划第一周-Tips-ControllerAdvice的使用的更多相关文章

  1. ARTS打卡计划第一周

    Algorithms: https://leetcode-cn.com/problems/two-sum/ Review: https://www.infoq.cn/article/EafgGJEtq ...

  2. ARTS打卡计划第一周-Share-系统字典模块的设计

    在软件开发的过程,经常有一些类型的字段信息:性别.学历.职级.车辆类别.公司类型.结算类型等.这些字段有2个特征:1是字段可选的类型是有限,2是字段可能会变化,我们把这种字段描述为字段字段.  本篇文 ...

  3. ARTS打卡计划第一周-Review

    本周分享的文章来自于medium的 Testing Best Practices for Java + Spring Apps 这个文章主要讲的是java测试的一些最佳实践 1.避免函数返回void, ...

  4. ARTS打卡计划第一周-Algorithm

    7. Reverse Integer import math class Solution: def reverse(self, x: int) -> int: ret = 0 if x > ...

  5. ARTS打卡计划第二周

    Algorithms: https://leetcode-cn.com/problems/3sum/ 算法是先排序,然后按照两个数和两边逼中,考虑去重. Review: https://www.inf ...

  6. ARTS打卡计划第二周-Review

    本周review的文章是:https://medium.com/@hakibenita/optimizing-django-admin-paginator-53c4eb6bfca3 改篇文章的题目是: ...

  7. ARTS打卡计划第九周

    Algorithms: https://leetcode-cn.com/problems/merge-two-sorted-lists/submissions/ 合并两个链表 Review:  “Pu ...

  8. ARTS打卡计划第二周-Share-使用java注解对方法计时

    现在有这样一种常见,系统中有一个接口,该接口执行的方法忽快忽慢,因此你需要去统计改方法的执行时间.刚开始你的代码可能如下: long start = System.currentTimeMillis( ...

  9. ARTS打卡计划第二周-Tips-mysql-binlog-connector-java的使用

    最近发现一个挺不错的框架mysql-binlog-connector-java,可以实时监控binlog的变化. 首先检查mysql的binlog是否开启,在开启的情况下: 引入依赖 <depe ...

随机推荐

  1. xmind 8 便携版:关联文件后,双击打开文件,在当前文件夹产生configuration子文件的问题解决办法

    Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\.xmind] @="XMind.Workbook.3" " ...

  2. sed指令的奇淫技巧

    查看某一个文件第5行和第10行sed -n '5,10p' filename 这样你就可以只查看文件的第5行到第10行. 查看某文件中指定第几行内容可以用sed -n '100{p;q}' filen ...

  3. mat函数

    mat函数可以将目标数据的类型转换为矩阵(matrix) data=[[1,1,0,3,1],[1,0,1,4,3],[1,0,1,2,4],[0,1,1,1,2], [2,0,0,3,0],[1,0 ...

  4. 分布式-JOB(XXL-Job)

    为什么使用xxl-job,不使用qz: 缺少补偿机制 不支持集群 不支持路由策略 统计任务执行 平台管理 监控,报警邮箱 幂等性:一次请求和多次请求得到相同的结果,不会因为多次的请求,导致最后的数据不 ...

  5. js判断数组里是否有重复元素的方法

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/longzhoufeng/article/details/78840974 第一种方法:但是下面的这种 ...

  6. SketchUp 建模练习(一)从图像建模运货木板 Pallet

    软件环境 SketchUp Pro 2017 GIMP 2.10.6 参考书籍 Google SketchUp for Game Design 作者:Robin de Jongh 运货木板效果图 制作 ...

  7. MySQL 之 MHA + ProxySQL + keepalived 实现读写分离,高可用(三)

    设置Keepalived VIP切换邮件告警 修改keepalived.conf配置: [root@server01 keepalived]# cat keepalived.conf ! Config ...

  8. Docker使用Link与newwork在容器之间建立连接

    一,使用 --link容器互联 docker 默认使允许container 互通的(通过-icc=false 关闭互通)同一个宿主机上的多个docker容器之间如果想进行通信,可以通过使用容器的ip地 ...

  9. Egret飞行模拟-开发记录03-LoadingUI界面

    一.非EUI方式 1.LoadingUI里的代码.class LoadingUI extends egret.Sprite implements RES.PromiseTaskReporter { p ...

  10. List集合去重

    本篇包含了两种去重,一种是List集合去重,一种是两个List集合去重合并 List集合去重,一般是两种方式,一种是遍历list集合判断后赋给另一个list集合,一种是用赋给set集合再返回给list ...