SpringBoot定制错误的Json数据

(1)自定义异常处理&返回定制Json数据

复制代码
 1 @ControllerAdvice
 2 public class MyExceptionHandler {
 3     @ResponseBody
 4     @ExceptionHandler(UserNotExistException.class)
 5     public Map<String,Object> handleException(Exception e){
 6         Map<String,Object> map = new HashMap<>();
 7         map.put("code",404);
 8         map.put("message",e.getMessage());
 9         return map;
10     }
11 }
复制代码

缺点:没有自适应效果,只是会返回自定义的json数据

(2)

复制代码
 1 @ControllerAdvice
 2 public class MyExceptionHandler {
 3     @ExceptionHandler(UserNotExistException.class)
 4     public String handleException(Exception e, HttpServletRequest request){
 5         //Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
 6         //传入我们自己的错误状态码,4xx,5xx,否则不会进入定制错误页面的解析流程
 7         request.setAttribute("javax.servlet.error.status_code",500);
 8         Map<String,Object> map = new HashMap<>();
 9         map.put("code",404);
10         map.put("message",e.getMessage());
11         return "forward:/error";
12     }
13 }
复制代码

缺点:可以自适应页面(浏览器返回错误页面,客户端返回Json数据),但不会携带我们自定义数据

(3)

1 public class MyErrorAttributes extends DefaultErrorAttributes {
2     @Override
3     public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
4         Map<String, Object> map =  super.getErrorAttributes(webRequest, includeStackTrace);
5         map.put("msg","coreqi");
6         return map;
7     }
8 }

响应自适应,可以携带我们自定义的数据

作者:奇

出处:https://www.cnblogs.com/fanqisoft/p/10324837.html

版权:本作品采用「本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。」许可协议进行许可。

posted @   SpringCore  阅读(1138)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
more_horiz
keyboard_arrow_up light_mode palette
选择主题
点击右上角即可分享
微信分享提示