spring boot配置全局异常拦截器

在Spring Boot中,可以通过配置全局异常拦截器来统一处理应用程序中的异常。下面是配置全局异常拦截器的详细流程:

  1. 创建一个异常处理类(ExceptionHandler):这个类负责处理应用程序中的异常。可以使用@ControllerAdvice注解将它标记为全局异常处理类。
@ControllerAdvice
public class ExceptionHandler {
    
    
    // 异常处理方法
    @org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleException(Exception ex) {
    
    
        // 创建一个ErrorResponse对象,设置错误信息
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setMessage(ex.getMessage());
        errorResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());

        // 返回包含错误信息的ResponseEntity对象
        return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
  1. 配置全局异常拦截器:在Spring Boot的配置类中,通过@EnableWebMvc注解启用MVC配置,并注册全局异常拦截器。
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
    
    
    @Autowired
    private ExceptionHandler exceptionHandler;

    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
    
    
        resolvers.add(new ExceptionHandlerExceptionResolver(exceptionHandler));
    }
}
  1. 自定义异常类:为了更好地处理不同类型的异常,可以自定义异常类,并在需要的地方抛出这些异常。
public class CustomException extends Exception {
    
    
    public CustomException(String message) {
    
    
        super(message);
    }
}
  1. 在控制器中抛出异常:在控制器中,可以通过抛出自定义异常来触发全局异常拦截器的处理。
@RestController
public class MyController {
    
    
    @GetMapping("/hello")
    public String hello() throws CustomException {
    
    
        throw new CustomException("Custom Exception");
    }
}

通过以上步骤,就可以配置全局异常拦截器来统一处理应用程序中的异常。当控制器中抛出自定义异常时,全局异常拦截器会捕获到该异常,并执行相应的异常处理方法,返回包含错误信息的ResponseEntity对象。这样,可以实现统一的异常处理逻辑,避免在每个控制器方法中重复处理异常。

猜你喜欢

转载自blog.csdn.net/kkwyting/article/details/133387007