截取Spring框架自动抛出异常

在Spring框架中,特别是使用Spring MVC或Spring Boot时,可以采用以下几种方式来截取和处理框架自动抛出的异常,使其更加符合应用的需求和提升用户体验:

1. 全局异常处理器 - @ControllerAdvice

使用@ControllerAdvice注解定义一个全局异常处理类,可以捕获整个应用程序中控制器抛出的异常。

示例代码:

Java
1import org.springframework.http.ResponseEntity;
2import org.springframework.web.bind.annotation.ControllerAdvice;
3import org.springframework.web.bind.annotation.ExceptionHandler;
4import org.springframework.web.client.HttpClientErrorException;
5
6@ControllerAdvice
7public class GlobalExceptionHandler {
8
9    @ExceptionHandler(value = {HttpClientErrorException.class})
10    public ResponseEntity<String> handleHttpClientErrorException(HttpClientErrorException e) {
11        // 处理特定异常,例如HttpClientErrorException
12        return ResponseEntity.status(e.getStatusCode()).body("发生错误:" + e.getMessage());
13    }
14
15    @ExceptionHandler(value = {Exception.class})
16    public ResponseEntity<String> handleGeneralException(Exception e) {
17        // 处理其他未被捕获的异常
18        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误:" + e.getMessage());
19    }
20}

2. 实现 HandlerExceptionResolver

实现HandlerExceptionResolver接口,可以对所有控制器方法抛出的异常进行处理。

示例代码:

Java
1import org.springframework.web.servlet.HandlerExceptionResolver;
2import org.springframework.web.servlet.ModelAndView;
3
4public class CustomExceptionResolver implements HandlerExceptionResolver {
5
6    @Override
7    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
8        // 根据异常类型自定义处理逻辑
9        if (ex instanceof NullPointerException) {
10            // 处理NullPointerException
11        } else if (ex instanceof IllegalArgumentException) {
12            // 处理IllegalArgumentException
13        } else {
14            // 默认处理逻辑
15        }
16        // 返回ModelAndView以控制视图和模型数据
17    }
18}

别忘了将自定义的异常解析器添加到Spring的配置中。

3. 使用AOP(面向切面编程)

通过AOP可以拦截方法调用,捕获并处理异常。

示例代码:

Java
1import org.aspectj.lang.annotation.Aspect;
2import org.aspectj.lang.annotation.AfterThrowing;
3import org.springframework.stereotype.Component;
4
5@Aspect
6@Component
7public class ExceptionHandlingAspect {
8
9    @AfterThrowing(pointcut = "execution(* com.yourpackage.controller.*.*(..))", throwing = "ex")
10    public void handleControllerExceptions(Exception ex) {
11        // 在这里处理控制器抛出的异常
12    }
13}

4. 在具体Controller中使用@ExceptionHandler

直接在控制器类中使用@ExceptionHandler注解,处理该控制器内抛出的特定异常。

示例代码:

Java
1@RestController
2public class MyController {
3
4    @ExceptionHandler(value = ResourceNotFoundException.class)
5    public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException ex) {
6        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
7    }
8
9    // ...其他方法
10}

通过这些方式,你可以有效地截取并定制Spring框架自动抛出的异常处理逻辑,提供更友好的错误反馈和提升应用的健壮性。

posted @ 2024-05-15 17:45  jason47  阅读(2)  评论(0编辑  收藏  举报