springboot统一异常处理

1.在Spring Boot中,您可以使用@ControllerAdvice和@ExceptionHandler2注解来实现统一的异常处理。以下是一个示例:
2.创建一个全局异常处理类,使用@ControllerAdvice注解标记,并定义一个或多个@ExceptionHandler方法来处理不同类型的异常。

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception ex) {
        // 处理通用异常
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal Server Error");
    }

    @ExceptionHandler(YourCustomException.class)
    public ResponseEntity<String> handleYourCustomException(YourCustomException ex) {
        // 处理自定义异常
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
    }

    // 添加其他异常处理方法...
}

在上面的示例中,我们创建了一个GlobalExceptionHandler类,并在类上使用了@ControllerAdvice注解。然后,我们定义了两个异常处理方法:handleException用于处理通用异常,handleYourCustomException用于处理自定义异常YourCustomException。您可以根据需要添加其他异常处理方法。

3.在应用程序中的其他控制器中,如果抛出了被@ExceptionHandler注解标记的异常,将会自动触发对应的异常处理方法。

@RestController
public class MyController {

    @GetMapping("/hello")
    public String hello() {
        // 抛出YourCustomException异常,将由GlobalExceptionHandler中的handleYourCustomException方法处理
        throw new YourCustomException("Custom Exception Occurred");
    }

    // 添加其他请求处理方法...
}

在上述示例中,当访问/hello路径时,会抛出YourCustomException异常,然后由GlobalExceptionHandler中的handleYourCustomException方法来处理。

通过以上的设置,当应用程序中的控制器抛出异常时,会根据异常类型自动触发对应的异常处理方法,并返回适当的HTTP响应。这样可以实现统一的异常处理,并返回一致的错误响应给客户端。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值