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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值