springboot自定义异常及配置全局异常捕获

在一个项目中的异常我们我们都会统一进行处理的,那么如何进行统一进行处理呢?
当然是配置一个全局异常进行捕获。
那我们需要怎么配置呢?
下来我们就来进行全局异常捕获的配置

全局异常捕获我们需要用到spring-boot-starter-web中的@ControllerAdvice注解,
ControllerAdvice本质上是一个Component,因此也会被当成组建扫描

使用@ControllerAdvice可以将所有的@ExceptionHandler方法都集中在一个类中,统一处理
1、@ControllerAdvice默认拦截所有控制器
2、@ControllerAdvice(annotaions={UserController.class})配置指定需要拦截的控制器
3、ControllerAdvice(basePackages = “com.demo”) 配置需要拦截的指定路径下的控制器
所以要是用@ControllerAdvice必须引入springboot-web依赖

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

定义一个全局处理异常的类

@ControllerAdvice//标注未全局异常处理
public class GlobalDefaultExceptionHandler {

    @ExceptionHandler(value = CustomRuntimeException.class)
    public void customRuntimeException(HttpServletRequest request,Exception e){
        System.out.println("自定义RuntimeException异常"+e.getMessage());
    }

    @ExceptionHandler(value = CustomException.class)
    public void customException(HttpServletRequest request,Exception e){
        System.out.println("自定义Exception异常"+e.getMessage());
    }
    /**
     * 处理空指针异常
     * 可以返回页面模板,也可以返回json数据
     */
    @ExceptionHandler(value = NullPointerException.class)
    public ModelAndView  NullExceptionHandler(HttpServletRequest request,Exception e){
        ModelAndView mv = new ModelAndView();
        e.printStackTrace();
        System.out.println("发生了空指针异常"+e.getMessage());
        mv.addObject("message",e);
        mv.setViewName("my error view");
        return mv;
    }

    /**
     * 处理其他异常
     * @param request
     * @param e
     */
    @ExceptionHandler(value = Exception.class)
    public void defaultErrorHandler(HttpServletRequest request,Exception e){
        System.out.println("其他异常"+e.getMessage());

    }
}

测试全局异常的controller

@RestController
@RequestMapping
public class ExceptionTestController {
    @RequestMapping("/zeroException")
    public int zeroException() {
        return 100 / 0;
    }

    @RequestMapping("/nullException")
    public int nullException() {
        String age = null;
        return age.length();
    }

    @RequestMapping("/customException/{age}")
    public void customException(@PathVariable(name = "age") Integer age) throws CustomException {
        if (5 - age < 0) {
            throw new CustomException("age大于5");
        }
    }


    @RequestMapping("/customRuntimeException/{age}")
    public void customRuntimeException(@PathVariable(name = "age") Integer age){
        if (5 - age < 0) {
            throw new CustomRuntimeException(20,"age大于5");
        }
    }
}

下面是自定义异常的类

public class CustomException extends Exception{
    private String message;

    public CustomException(String message) {
        super(message);
        this.message=message;
    }

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

}
public class CustomRuntimeException extends RuntimeException{

    private Integer  ErrorCode;
    private String ErrorMessage;

    public CustomRuntimeException(Integer errorCode, String errorMessage) {
        super(errorMessage);
        ErrorCode = errorCode;
        ErrorMessage = errorMessage;
    }

    public Integer getErrorCode() {
        return ErrorCode;
    }

    public void setErrorCode(Integer errorCode) {
        ErrorCode = errorCode;
    }

    public String getErrorMessage() {
        return ErrorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        ErrorMessage = errorMessage;
    }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值