如何使用SpringBoot全局异常处理?有效提升开发效率

一、如何使用springboot全局异常处理?

在 Spring Boot 中,可以使用 @ControllerAdvice 和 @ExceptionHandler 注解来实现全局异常处理。具体步骤如下:

二、使用步骤

1.创建一个异常处理类:

代码如下:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
    }

    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity<String> handleNullPointerException(NullPointerException e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("空指针异常");
    }

    @ExceptionHandler(ArithmeticException.class)
    public ResponseEntity<String> handleArithmeticException(ArithmeticException e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("算术异常");
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("非法参数异常");
    }
}

2.在启动类中注册异常处理类:

代码如下:

@SpringBootApplication
@Import(GlobalExceptionHandler.class)
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

在上面的代码中,我们使用 @Import 注解将 GlobalExceptionHandler 类注册到 Spring 容器中,这样当应用程序抛出异常时,就会自动调用相应的处理方法。

3.在控制器中测试异常处理:

@RestController
public class DemoController {

    @GetMapping("/test")
    public String test() {
        String str = null;
        str.length();
        return "test";
    }
}


在上面的代码中,我们故意让 str 为空,并调用其 length() 方法抛出空指针异常。当我们访问 /test 路径时,就会触发 GlobalExceptionHandler 中的 handleNullPointerException 方法,返回自定义的错误信息 “空指针异常”。

总结

总的来说,使用全局异常处理可以统一处理应用程序中的异常,避免代码中到处都是 try-catch 块,并且可以返回自定义的错误信息,方便调试和排查问题。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值