springMvc统一异常处理

程序你得看得懂 2024-02-24 03:02:12

在Spring MVC中,统一异常处理通常是通过实现HandlerExceptionResolver接口或使用@ControllerAdvice和@ExceptionHandler注解来完成的。下面是两种方法的示例:

方法1:使用@ControllerAdvice和@ExceptionHandler

这种方法更简洁,适用于大多数场景。你可以定义一个全局的异常处理类,并通过@ControllerAdvice注解来使其生效。然后在该类中定义不同的@ExceptionHandler方法来处理不同的异常。

import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public GlobalExceptionHandler { @ExceptionHandler(value = Exception.class) public ResponseEntity<Object> exception(Exception exception) { // 这里可以记录日志等操作 return new ResponseEntity<>("发生异常:" + exception.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(value = YourCustomException.class) public ResponseEntity<Object> yourCustomException(YourCustomException exception) { // 这里可以记录日志等操作 return new ResponseEntity<>("自定义异常:" + exception.getMessage(), HttpStatus.BAD_REQUEST); } }方法2:实现HandlerExceptionResolver接口

这种方法更复杂,但提供了更多的灵活性。你需要实现HandlerExceptionResolver接口,并在resolveException方法中处理异常。

import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public GlobalExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) { // 这里可以根据不同的异常类型进行不同的处理 // 例如,你可以设置不同的HTTP状态码,或者返回不同的错误信息 // 假设我们只处理自定义异常,其他异常不处理 if (exception instanceof YourCustomException) { // 这里可以记录日志等操作 response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return new ModelAndView("errorView", "message", "自定义异常:" + exception.getMessage()); } // 返回null表示该异常不由这个解析器处理 return null; } }

然后,你需要在Spring配置中注册这个异常解析器:

import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public WebConfig implements WebMvcConfigurer { @Override public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) { resolvers.add(new GlobalExceptionResolver()); } }

注意,如果同时使用了@ControllerAdvice和HandlerExceptionResolver,Spring会先调用HandlerExceptionResolver,如果它返回了null,则会继续调用@ControllerAdvice中的方法。

对于API返回,通常会使用ResponseEntity来封装返回的数据和HTTP状态码。在上面的@ControllerAdvice示例中,已经展示了如何使用ResponseEntity来返回错误信息。在实际应用中,你还可以根据需要封装更多的信息,如错误代码、详细描述等。

0 阅读:6

程序你得看得懂

简介:感谢大家的关注