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

  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. Linux系统下安装Angular2开发环境(Ubuntu16.0和deepin)

    说明下,以下过程都是在ubuntu16.0系统下,win系统环境下的安装过程更简单,基本上可以仿效此环境来,除了不用配置系统命令(win下自动可以),node安装是exe程序,一键安装.另外,这里面像 ...

  2. Internet Explorer 安全区域注册表项说明

    引用网址:http://support.microsoft.com/kb/182569/zh-cnInternet Explorer 安全区域设置存储在以下注册表子项下面: HKEY_LOCAL_MA ...

  3. 【CentOS】PostgreSQL安装与设定

    本教程适合Centos6.7或者RedHat. PostgreSQL安装 1.Postgresql安装包确认 yum list postgresql* postgresql-server.x86_64 ...

  4. C# Xamarin开发 GenyMotion adb List of devices attached

    最近,公司要求要学习Xamarin,说是将来用到PDA上,所以最近对XaMarin开始接触,16年的时候就听说.Net开始着实跨平台,安卓和IOS,但是网上看过很多资料都说Xamarin比较坑,一般的 ...

  5. sed命令的基本使用方法

    sed命令 stream editor,用程序的方式编辑文本.基本上是玩正则模式匹配. 用s命令替换 $ sed "s/my/Hao Chen's/g" pets.txt 单引号去 ...

  6. 删除DataTable的指定行(Lambda)

    DataTable dtTcu = GetAllTcuInfoBySdId(sdId); DataTable dtToesm = GetAllToesmBySdId(sdId); foreach (D ...

  7. 在linux中输出每个group的用户成员

    先提供使用文件一步一步获取相关信息: 1. 获取所有的用户: awk -F: '{print $1 > "1.txt"}' /etc/passwd 2. 获取每个用户, 及其 ...

  8. nginx+多个tomcat

    学习nginx的时候遇到的问题:nginx怎么部署两台tomcat?   upstream 在网上找的资源,我在nginx配置文件(nginx.conf)中添加了两个server.结果只显示第一个se ...

  9. solr中Cache综述

    一.概述 Solr查询的核心类就是SolrIndexSearcher,每个core通常在同一时刻只由当前的SolrIndexSearcher供上层的handler使用(当切换SolrIndexSear ...

  10. Python 内置函数math,random

    内置函数的一些操作 - math(数学模块) - random(随机模块) - 使用内置函数时注意需要导入 math - (ceil)向上取整,返回取整数 # 向上取整,返回向上取整的数 import ...