Springboot- 统一结果集+全局异常+自定义异常

1、R全局泛型返回对象

@Data
public class R<T> {

    private Integer code; //编码:1成功,0和其它数字为失败

    private String msg; //错误信息

    private T data; //数据

    private Map map = new HashMap(); //动态数据

    public static <T> R<T> success(T object) {
        R<T> r = new R<T>();
        r.data = object;
        r.code = 1;
        return r;
    }

    public static <T> R<T> error(String msg) {
        R r = new R();
        r.msg = msg;
        r.code = 0;
        return r;
    }

    public R<T> add(String key, Object value) {
        this.map.put(key, value);
        return this;
    }
}

2、GlobalExceptionHandler全局异常处理

package com.example.common;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

//Controller通知(作用地址)
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 空指针异常
     */
    //异常处理注解
    @ExceptionHandler(value = NullPointerException.class)
    public R exceptionHandler(NullPointerException e) {
        log.error("空指针异常");
        return  R.error("空指针异常");
    }

    /**
     * 其他异常
     */
    @ExceptionHandler(value = Exception.class)
    public R exception(Exception e) {
        log.error("500异常:" + e);
        return  R.error("500异常");
    }

    /**
     * 参数校验异常
     */
    @ExceptionHandler(BindException.class)
    public R bindException(BindException e) {
        // 然后提取错误提示信息进行返回
        log.error("参数校验异常:" + e.getBindingResult().getFieldError().getDefaultMessage());
        return R.error("参数校验异常:" + e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 请求参数异常
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public R missingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error("请求参数异常" + e);
        return  R.error("缺少请求参数:" + e.getParameterName());
    }

  /**
     * 自定义异常处理方法
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException e){
        log.error("自定义异常"+e);
        return R.error("自定义异常");
    }
}

controller


    @RequestMapping("/test")
    public R<String> test() {
        return R.success("ok");
    }

html界面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试使用</title>
    <script src="js/jquery-3.6.0.js"></script>
    <script>
        function add() {
            $.post({
                url: "/R/test",
                contentType: "application/json",
                data: JSON.stringify({
                    "gridId": "12",
                    "gridName": "mjz",
                    "gridType": "社区网格",
                    "managerId": 1,
                    "isborder": 1,
                }),
                success: function (data) {
                    alert("添加成功")
                }
            })
        }
    </script>
</head>
<body>

<input class="button" onclick="add()" type="button" value="测试">

</body>
</html>

成功结果,成功返回R<String>对象

 自定义业务异常类(记得加入全局异常处理类中,规范化)

package com.example.common;

/**
 * 自定义业务异常类
 */
public class CustomException extends RuntimeException {
}

controller,手动抛出自定义异常,其他异常也一样

    @SneakyThrows
    @RequestMapping("/test")
    public R<String> test() {
        throw new CustomException();
//        return R.success("ok");
    }

结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晚霞虽美不如你

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值