SpringController返回值和异常自动包装

今天遇到一个需求,在不改动原系统代码的情况下。将Controller的返回值和异常包装到一个统一的返回对象中去。

例如原系统的接口

public String myIp(@ApiIgnore HttpServletRequest request);

返回的只是一个IP字符串"0:0:0:0:0:0:0:1",目前接口需要包装为:

{"code":200,"message":"","result":"0:0:0:0:0:0:0:1","success":true}

而原异常跳转到error页面,需要调整为

{
  "success": false,
  "message": "For input string: \"fdsafddfs\"",
  "code": 500,
  "result": "message"
}

因此就有了2个工作子项需要完成:

1)Exception的处理

2)controller return值的处理

Exception的自动包装

返回的exception处理可以采用@RestControllerAdvice来处理。

建立自己的Advice类,注入国际化资源(异常需要支持多语言)
 

package org.ccframe.commons.mvc;import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.ccframe.commons.filter.CcRequestLoggingFilter;
import org.ccframe.commons.util.BusinessException;
import org.ccframe.config.GlobalEx;
import org.ccframe.subsys.core.dto.Result;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.core.MethodParameter;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.NoHandlerFoundException;import javax.servlet.http.HttpServletRequest;
import java.util.Locale;@RestControllerAdvice
@Log4j2
public class GlobalRestControllerAdvice{private MessageSource messageSource; //国际化资源private LocaleResolver localeResolver;private Object[] EMPTY_ARGS = new Object[0];public GlobalRestControllerAdvice(MessageSource messageSource, LocaleResolver localeResolver){this.messageSource = messageSource;this.localeResolver = localeResolver;}private Result<String> createError(HttpServletRequest request, Exception e,int code, String msgKey, Object[] args){Locale currentLocale = localeResolver.resolveLocale(request);String message = "";try {message = messageSource.getMessage(msgKey, args, currentLocale);}catch (NoSuchMessageException ex){message = e.getMessage();}finally {log.error(message);CcRequestLoggingFilter.pendingLog(); //服务器可以记录出错时的请求啦😂}return Result.error(code, message, msgKey);}@ExceptionHandler(NoHandlerFoundException.class)public Result<?> handlerNoFoundException(HttpServletRequest request, Exception e) {return createError(request, e, HttpStatus.SC_NOT_FOUND, "error.mvc.uriNotFound", EMPTY_ARGS);}@ExceptionHandler(HttpRequestMethodNotSupportedException.class)public Result<?> httpRequestMethodNotSupportedException(HttpServletRequest request, HttpRequestMethodNotSupportedException e){return createError(request,e, HttpStatus.SC_NOT_FOUND,"error.mvc.methodNotSupported",new Object[]{e.getMethod(), StringUtils.join(e.getSupportedMethods(), GlobalEx.DEFAULT_TEXT_SPLIT_CHAR)});}@ExceptionHandler(BusinessException.class)public Result<?> businessException(HttpServletRequest request, BusinessException e){return createError(request,e, HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMsgKey(), e.getArgs());}@ExceptionHandler(ObjectOptimisticLockingFailureException.class) //乐观锁异常public Result<?> objectOptimisticLockingFailureException(HttpServletRequest request, ObjectOptimisticLockingFailureException e){return createError(request,e, HttpStatus.SC_INTERNAL_SERVER_ERROR, "errors.db.optimisticLock", EMPTY_ARGS);}@ExceptionHandler(MaxUploadSizeExceededException.class) // 文件上传超限,nginx请设置为10Mpublic Result<?> handleMaxUploadSizeExceededException(HttpServletRequest request, MaxUploadSizeExceededException e) {return createError(request, e, HttpStatus.SC_INTERNAL_SERVER_ERROR, "error.mvc.fileTooLarge", EMPTY_ARGS);}@ExceptionHandler(Exception.class)@ResponseBodypublic Result<?> handleException(HttpServletRequest request, Exception e) {log.error(e);return createError(request,e, HttpStatus.SC_INTERNAL_SERVER_ERROR, "message", new Object[]{e.getMessage()});}
}

在Config类初始化该Bean(当然也可以使用@Component支持扫描,随你喜欢)
 

	@Beanpublic GlobalRestControllerAdvice globalRestControllerAdvice(MessageSource messageSource, LocaleResolver localeResolver){return new GlobalRestControllerAdvice(messageSource, localeResolver);}

controller return值的自动包装

网上的例子有很多坑,包括使用HandlerMethodReturnValueHandler,看了源码才发现。还是ResponseBodyAdvice好使。

建立自己的处理Bean

package org.ccframe.commons.mvc;import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import org.apache.http.HttpStatus;
import org.ccframe.commons.util.JsonUtil;
import org.ccframe.subsys.core.dto.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import springfox.documentation.swagger.web.ApiResourceController;import java.util.regex.Pattern;@ControllerAdvice
public class CcResponseBodyAdvice implements ResponseBodyAdvice<Object> {private static final Pattern CONTROLLER_PATTERN = Pattern.compile("^org\\.ccframe\\.(subsys|sdk)\\.[a-z0-9]+\\.controller\\.");@Overridepublic boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {return // 只有自己的cotroller类才需要进入,否则swagger都会挂了
CONTROLLER_PATTERN.matcher(returnType.getContainingClass().getName()).find();}@Overridepublic Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {System.out.println(returnType.getContainingClass());Result<Object> result = new Result<>();result.setResult(body);result.setCode(HttpStatus.SC_OK);if(body instanceof String){ //String返回要特殊处理return JSON.toJSONString(result);}else {return result;}}
}

如果你不需要根据正则来指定包,可以直接用RestControllerAdvice的basePackages属性来过滤

注意这里有2个坑

1)String类型的返回被其它的转换接口StringHttpMessageConverter处理,因此返回要进行JSON编码而不能返回其他类型,否则会报cast类型错,因此就有了String部分的特殊处理方法。

2)controller方法签名返回是void时,不会被处理

在Config类初始它:
 

	@Beanpublic CcResponseBodyAdvice ccResponseBodyAdvice() {return new CcResponseBodyAdvice();}

最后。上面两个Bean也可以写在一个,有兴趣的自己尝试。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/738639.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C++从零开始(day48)——map再深理解

这是关于一个普通双非本科大一学生的C的学习记录贴 在此前&#xff0c;我学了一点点C语言还有简单的数据结构&#xff0c;如果有小伙伴想和我一起学习的&#xff0c;可以私信我交流分享学习资料 那么开启正题 今天分享的是关于set和map的知识点 1.map的operator[ ] 1.1介绍…

20240309web前端_第一周作业_豆瓣电影

作业四&#xff1a;豆瓣电影 成果展示&#xff1a; 完整代码&#xff1a; <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0…

探索计算机视觉的未来

目录 前言1 计算机视觉简介2 计算机视觉的基本原理2.1 图像获取2.2 图像预处理2.3 特征提取2.4 模式识别 3 深度学习与计算机视觉3.1 深度学习的基本原理3.2 深度学习在计算机视觉中的应用 4 计算机视觉的应用领域4.1 人脸识别4.2 物体识别4.3 图像分割4.4 视频追踪 5 未来发展…

Linux系统——命令行速查表

目录 一、系统相关命令 二、硬件相关命令 三、用户相关命令 四、文件相关命令 五、进程相关命令 六、文件权限相关命令 七、网络相关命令 八、压缩/打包相关命令 九、安装包相关命令 十、安装源&#xff08;编译&#xff09;相关命令 十一、搜索相关命令 十二、登录…

Midjourney从入门到实战:图像生成命令及参数详解

目录 0 专栏介绍1 Midjourney Bot常用命令2 Midjourney绘图指令格式3 Midjourney绘图指令参数3.1 模型及版本3.2 画面比例3.3 风格化3.4 图片质量3.5 混乱值3.6 随机数种子3.7 重复贴图3.8 停止3.8 垫图权重3.9 提示词权重分割 0 专栏介绍 &#x1f525;Midjourney是目前主流的…

Vue3全家桶 - VueRouter - 【3】嵌套路由【children】

嵌套路由【children】 如果在路由视图中展示的组件包含自己的路由占位符&#xff08;路由出口&#xff09;&#xff0c;则此处会用到嵌套路由&#xff1b;如图所示&#xff1a;点击关于链接&#xff0c;则会展示About组件&#xff0c;在其组件中又包含了路由链接和路由占位符&…

蓝桥杯-ISBN号码

此题然让本人纠结了很久&#xff0c;真的好多坑。。。。果然还是太菜了。 完整代码以及思路解析(在注释中) #include <iostream> using namespace std; int main() {string num;cin>>num; int count0;int w1;for(int i0;i<10;i){if((i!1)&&(i!5)) //坑…

常见的限流算法- python版本

shigen坚持更新文章的博客写手&#xff0c;擅长Java、python、vue、shell等编程语言和各种应用程序、脚本的开发。记录成长&#xff0c;分享认知&#xff0c;留住感动。 个人IP&#xff1a;shigen 在系统的稳定性设计中&#xff0c;需要考虑到的就是限流&#xff0c;避免高并发…

【MySQL】ROW_NUMBER 窗口函数妙用之报告系统状态的连续日期

力扣题 1、题目地址 1225. 报告系统状态的连续日期 2、模拟表 表&#xff1a;Failed Column NameTypefail_datedate 该表主键为 fail_date (具有唯一值的列)。该表包含失败任务的天数. 表&#xff1a; Succeeded Column NameTypesuccess_datedate 该表主键为 success_…

Elastic Stack--08--SpringData框架

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 SpringData[官网&#xff1a; https://spring.io/projects/spring-data](https://spring.io/projects/spring-data) Spring Data Elasticsearch 介绍 1.SpringData-…

AI+X 高校行:首场浙大站爆满!

Datawhale线下 线下活动&#xff1a;AIX 高校行活动 AIX&#xff1a;希望将人工智能&#xff08;AI&#xff09;与各个学科和行业&#xff08;X&#xff09;结合&#xff0c; 激发无限潜力和创造力&#xff08;X&#xff09;&#xff0c;让年轻人拥有更多可能性&#xff08;X&…

Discord OAuth2授权以及机器人监听群事件

下面文章讲解获取OAuth2授权整个流程&#xff0c;创建机器人&#xff0c;使用机器人监听工会&#xff08;工会就是创建的服务器&#xff09;成员变化等等&#xff0c;对接国外的都是需要VPN的哦&#xff0c;对接的时候记得提前准备。 创建应用 点击 此页面添加应用,&#xff…

Midjourney绘图欣赏系列(七)

Midjourney介绍 Midjourney 是生成式人工智能的一个很好的例子&#xff0c;它根据文本提示创建图像。它与 Dall-E 和 Stable Diffusion 一起成为最流行的 AI 艺术创作工具之一。与竞争对手不同&#xff0c;Midjourney 是自筹资金且闭源的&#xff0c;因此确切了解其幕后内容尚不…

[C++] C++生成随机数

一、简介 在C语言中常使用srand()random()的方式生成随机数&#xff0c;该方式并不是一个很好的随据说生成方法&#xff0c;一方面是因为其生成的随机数质量较低&#xff0c;另一方面其随机数范围也有所限制。在C11中推荐使用随机数引擎的方式生成随机数。 如何高效得生成高质…

JavaWeb - Expected URL scheme ‘http‘ or ‘https‘ but no colon was found

问题描述 Expected URL scheme http or https but no colon was found 原因分析 一般是代码中 HttpClient 或其他远程请求中 URL 为 null 引起的 解决方案 检查调试代码请求中的 URL 是否为空&#xff0c;根据业务解决即可~

【wps】wps与office办公函数储备使用(结合了使用案例 持续更新)

【wps】wps与office办公函数储备使用(结合了使用案例 持续更新) 1、TODAY函数 返回当前电脑系统显示的日期 TODAY函数&#xff1a;表示返回当前电脑系统显示的日期。 公式用法&#xff1a;TODAY() 2、NOW函数 返回当前电脑系统显示的日期和时间 NOW函数&#xff1a;表示返…

安装CDH平台的服务器磁盘满了,磁盘清理过程记录

1.使用hdfs命令查看哪个文件占用最大 hdfs dfs -du -h /tmp 2.我的服务器上显示/tmp/hive/hive文件夹下的&#xff0c;一串字符串命名的文件特别大几乎把磁盘占满了 网上查到/tmp文件是临时文件&#xff0c;由于hiveserver2任务运行异常导致缓存未删除&#xff0c;正常情况下…

蚂蚁链摩斯荣获“艾瑞保险业数字化卓越服务商“奖

近日&#xff0c;艾瑞咨询发布《2023年中国保险业数字化转型研究报告》&#xff0c;摩斯隐私计算解决方案被报告入选&#xff0c;并获得“保险业数字化卓越服务商”奖。 蚂蚁摩斯是隐私计算行业的领先布局者&#xff1a;早在2017年&#xff0c;蚂蚁集团启动了隐私计算项目&…

Linux操作系统-07-Linux安装应用

一、使用rpm安装应用&#xff08;不推荐&#xff09; 先下载到本地&#xff0c;以.rpm文件名结尾&#xff0c;下载完成后&#xff0c;再安装 rpm -qa | grep mysql #查询当前系统是否有下载过mysql包 先上传mysql的rpm安装包到linux的opt目录 安装 rpm -ivh …

Linux 多进程开发(上)

第二章 Linux 多进程开发 2.1 进程概述2.2 进程状态转换2.3 进程创建2.4 exec 函数族2.5 进程控制 网络编程系列文章&#xff1a; 第1章 Linux系统编程入门&#xff08;上&#xff09; 第1章 Linux系统编程入门&#xff08;下&#xff09; 第2章 Linux多进程开发&#xff08;…