ARTS打卡计划第一周-Tips-ControllerAdvice的使用
通常在开发具体项目过程中我们可能会面临如下问题:
- 统一所有的json返回结果
- 统一处理所有controller中的异常,并且给不同异常不同的返回状态值
- 统一对返回的接口做数据校验或者加密,防止篡改
在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的使用的更多相关文章
- ARTS打卡计划第一周
Algorithms: https://leetcode-cn.com/problems/two-sum/ Review: https://www.infoq.cn/article/EafgGJEtq ...
- ARTS打卡计划第一周-Share-系统字典模块的设计
在软件开发的过程,经常有一些类型的字段信息:性别.学历.职级.车辆类别.公司类型.结算类型等.这些字段有2个特征:1是字段可选的类型是有限,2是字段可能会变化,我们把这种字段描述为字段字段. 本篇文 ...
- ARTS打卡计划第一周-Review
本周分享的文章来自于medium的 Testing Best Practices for Java + Spring Apps 这个文章主要讲的是java测试的一些最佳实践 1.避免函数返回void, ...
- ARTS打卡计划第一周-Algorithm
7. Reverse Integer import math class Solution: def reverse(self, x: int) -> int: ret = 0 if x > ...
- ARTS打卡计划第二周
Algorithms: https://leetcode-cn.com/problems/3sum/ 算法是先排序,然后按照两个数和两边逼中,考虑去重. Review: https://www.inf ...
- ARTS打卡计划第二周-Review
本周review的文章是:https://medium.com/@hakibenita/optimizing-django-admin-paginator-53c4eb6bfca3 改篇文章的题目是: ...
- ARTS打卡计划第九周
Algorithms: https://leetcode-cn.com/problems/merge-two-sorted-lists/submissions/ 合并两个链表 Review: “Pu ...
- ARTS打卡计划第二周-Share-使用java注解对方法计时
现在有这样一种常见,系统中有一个接口,该接口执行的方法忽快忽慢,因此你需要去统计改方法的执行时间.刚开始你的代码可能如下: long start = System.currentTimeMillis( ...
- ARTS打卡计划第二周-Tips-mysql-binlog-connector-java的使用
最近发现一个挺不错的框架mysql-binlog-connector-java,可以实时监控binlog的变化. 首先检查mysql的binlog是否开启,在开启的情况下: 引入依赖 <depe ...
随机推荐
- redis订阅发布消息操作本地缓存
Redis 本地缓存+远程缓存方案 使用纯java的ehcache作为本地缓存 Reids 作为远程分布式缓存 解决redis缓存压力过大,提高缓存速度,以及缓存性能. Redis和ehcache缓存 ...
- C# Winform 中使用FTP实现软件自动更新功能
实现思路:通过访问FTP站点,将站点中的文件下载至软件指定位置. 第一步:FTP站点中导入需要下载更新的程序文件,并添加配置文件(配置下载后文件的下载路径),如下图所示: 第二步:Winfrom程序读 ...
- 【linux】之查看磁盘占用情况
查看整个硬盘使用情况: 1.df -h 2.du -bs xx 具体目录占用情况 3.查看当前目录大于100M的文件 find . -size +100M
- 学会学习:高效学习方式(使用vscode-snippet有感)
入职以来我们团队一直都在使用vscode编辑器,后来也有人开始使用webstorm.很久之前我突然为每天重复的编写.vue文件里面的export.<script lang="scss& ...
- css 优化
// 注: 以下内容大量借阅自<<Webkit技术内幕>>--朱永盛(14年出版的) , 很多内容可能早已更新 , 因此个人并不能确定论述是否正确.部分摘录内容有删减 , 目录 ...
- [UE4]抓取准备
一.引擎的VR实例工程是使用手柄进行抓取的.我们需要加上可以使用鼠标进行抓取操作. 二.将左右手保存到全局变量. 三.左右手分别调用抓取和扔方法
- 微软 workflow 工作流总结2
1.公共的状态机工作流 书签的设置 可以在判断模块中的action中赋值,因为在action中肯定要进入到下一个书签,所以可以在此给书签name赋值
- MAP File
https://warpproject.org/trac/wiki/howto/Linker_scripts_MAP_files Description A MAP file is an output ...
- 记录4-Ubuntu 16.04用gparted调整分区
几天在安装双系统时,没注意居然把swap分区设置成了50G.今天才发现,于是用gparted重新分区. 1. sudo apt-get install gparted 2. 重新用u盘启动进入ubun ...
- 跨年呈献:HP-Socket for Linux 1.0 震撼发布
三年,三年,又三年,终于,终于,终于不用再等啦!就在今天,HP-Socket for Linux v1.0 震撼发布!还是一样的接口,一样的高效,一样的简便,一样的味道. HP-Socket ...