面试题:Spring MVC 中如何处理异常?

在Spring MVC中,异常处理是一个重要的部分,确保应用程序在出现错误时能够优雅地响应。以下是几种常见的异常处理方式:

1. 使用 @ExceptionHandler 注解

@ExceptionHandler 注解用于在控制器内部处理特定异常。它可以处理控制器方法抛出的异常。

@Controller
public class MyController {

    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity<String> handleNullPointerException(NullPointerException ex) {
        return new ResponseEntity<>("NullPointerException occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @GetMapping("/test")
    public String test() {
        throw new NullPointerException("Null pointer exception");
    }
}

2. 使用 @ControllerAdvice 注解

@ControllerAdvice 注解用于全局异常处理,可以处理多个控制器抛出的异常。

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception ex) {
        return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException ex) {
        return new ResponseEntity<>("Resource not found: " + ex.getMessage(), HttpStatus.NOT_FOUND);
    }
}

3. 使用 @ResponseStatus 注解

@ResponseStatus 注解用于将特定异常映射到HTTP状态码。

@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Resource not found")
public class ResourceNotFoundException extends RuntimeException {
    // Constructor and other methods
}

4. 实现 HandlerExceptionResolver 接口

通过实现 HandlerExceptionResolver 接口,可以自定义异常处理逻辑。

@Component
public class CustomHandlerExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("error", ex.getMessage());
        modelAndView.setViewName("error");
        return modelAndView;
    }
}

5. 使用 SimpleMappingExceptionResolver

SimpleMappingExceptionResolver 是Spring提供的一个简单异常解析器,可以将异常映射到特定的视图。

@Bean
public SimpleMappingExceptionResolver simpleMappingExceptionResolver() {
    SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
    Properties mappings = new Properties();
    mappings.setProperty("java.lang.Exception", "error");
    resolver.setExceptionMappings(mappings);
    return resolver;
}

6. 使用 @RestControllerAdvice 注解

@RestControllerAdvice@ControllerAdvice@ResponseBody 的组合,适用于RESTful服务。

@RestControllerAdvice
public class RestGlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception ex) {
        return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

总结

  • @ExceptionHandler:用于控制器内部的异常处理。
  • @ControllerAdvice:用于全局异常处理。
  • @ResponseStatus:将异常映射到HTTP状态码。
  • HandlerExceptionResolver:自定义异常处理逻辑。
  • SimpleMappingExceptionResolver:将异常映射到视图。
  • @RestControllerAdvice:适用于RESTful服务的全局异常处理。

在面试中,理解这些异常处理方式及其适用场景是关键。

THE END
点赞13 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容