springboot使用@ControllerAdvice 捕抓全局异常-自定义异常

//这是全局拦截异常拦截器
package com.springboot.admin.exception;

import com.springboot.admin.Result;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class MyExceptionHandler {
    /**
     * 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器
     * @param binder
     */
    @InitBinder
    public void initWebBinder(WebDataBinder binder){

    }

    /**
     * 把值绑定到Model中,使全局@RequestMapping可以获取到该值
     * @param model
     */
    @ModelAttribute
    public void addAttribute(Model model) {
        model.addAttribute("attribute",  "The Attribute");
    }

    /**
     * 捕获MyException
     * @param e
     * @return json格式类型
     */
    @ResponseBody
    @ExceptionHandler({MyException.class}) //指定拦截异常的类型
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //自定义浏览器返回状态码
    public Result myExceptionHandler(MyException e) {
        return Result.error(e.getCode(), e.getMessage());
    }

    /**
     * 捕获Exception
     * @param e
     * @return json格式类型
     */
    @ResponseBody
    @ExceptionHandler({Exception.class}) //指定拦截异常的类型
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //自定义浏览器返回状态码
    public Result allExceptionHandler(Exception e) {
        return Result.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.toString());
    }

}

 

//这是我的自定义异常

package com.springboot.admin.exception;

public class MyException extends RuntimeException {
    private String message;
    private int code;

    public MyException(int code, String message) {
        super(message);
        this.message = message;
        this.code = code;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }
}

 

//测试

    public Result testException() throws Exception {
        Ups ups = upsMapper.selectById(1);
        ups.setUid(2);
        ups.setTypeId(8);
        upsMapper.updateById(ups);
        Ups ups1 = upsMapper.selectById(1);
        System.out.println("type_id----------------" + ups1.getTypeId());

//        int a = 1 / 0;

        throw new MyException(1, "打印错误信息");
    }

 

注意: 抛出异常时必须抛出 RuntimeException 才能捕捉到,另外,自定义异常也必须继承 RuntimeException  异常,否则也是无法捕捉的。RuntimeException  才能回滚

 

注意:尽量只拦截自定义异常,如果全部拦截,不方便查看所有报错信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值