SpringMVC异常处理之HandlerExceptionResolver

上一篇文章介绍了如何使用@ExceptionHandler注解来处理全局异常SpringMVC异常处理之ExceptionHandler,本篇文章主要介绍使用HandlerExceptionResolver处理异常。

public interface HandlerExceptionResolver {
	ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex);
}

HandlerExceptionResolver接口中定义了一个resolveException方法,用于处理Controller中的异常。Exception ex参数即Controller抛出的异常。返回值类型是ModelAndView,可以通过这个返回值来设置异常时显示的页面。

  1. 定义一个类实现HandlerExceptionResolver接口
@Component
public class  ExceptionHandler implements HandlerExceptionResolver {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
            Object o, Exception e) {
        String requestType = httpServletRequest.getHeader("X-Requested-With");
        String contentType = httpServletRequest.getContentType() == null ? "" : httpServletRequest.getContentType().toLowerCase();

        String message = e.getMessage();
        if (e instanceof GeneralException) { // 用户自定义异常
            message = ((GeneralException) e).getSimpleMessage();
        } else { // 通用异常
            message = "系统异常!";
        }
      
        // 判断是否是Ajax 请求
        if (contentType.contains("application/json") || (StringUtils.isNotEmpty(requestType)
                && ("XMLHttpRequest".equalsIgnoreCase(requestType))) {
            Assert.notNull(httpServletResponse);
            httpServletResponse.setContentType("text/json;charset=utf-8");
            ModelAndView modelAndView = new ModelAndView();
            // 返回异常信息(JSON)
            try  {
            	PrintWriter writer = httpServletResponse.getWriter()
                writer.write(message);
                writer.flush();
            } catch (IOException ignore) {
            } finally {
                modelAndView.clear();
                return modelAndView;
            }
        } else { // 页面跳转
            Map<String, Object> modal = new HashMap<>();
            modal.put("exceptionMessage", message);
            modal.put("ex", e);
            return new ModelAndView("error/error", modal);
        }
    }
}

2.在Controller方法中抛出异常

   @RequestMapping("test")
    public Object test() throws Exception {
        if ("XXXX".equals(type)) {
            // 由customGenericExceptionHnadler处理
            throw new GeneralException(ErrorCode.INTERNAL_ERROR, "XX错误");
        } 
        if ("YYYY".equals(type)) {
            // 由handleAllException处理
            throw new IOException();
        } 
       // 如果业务操作有异常,由handleAllException处理
    }

至此,ExceptionHandler即可对全局异常进行处理。


------------本文结束感谢您的阅读------------
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring MVC中,可以通过以下几种方式来处理异常: 1. 使用@ControllerAdvice注解和@ExceptionHandler注解: - 首先,创建一个全局的异常处理类,使用@ControllerAdvice注解标注,并在类中定义一个或多个带有@ExceptionHandler注解的方法,用于处理特定的异常类型。 - 在异常处理方法中,可以定义需要执行的逻辑,例如记录日志、返回自定义错误信息等。 - 这种方式可以捕获并处理控制器中抛出的异常,提供统一的异常处理机制。 2. 使用@ExceptionHandler注解: - 在控制器类中,可以使用@ExceptionHandler注解标注方法,用于处理特定的异常类型。 - 这种方式适合处理控制器中的异常,可以针对不同的异常类型定义不同的处理逻辑。 3. 使用HandlerExceptionResolver接口: - 可以实现HandlerExceptionResolver接口,并注册为Spring的bean。 - 通过实现该接口的resolveException方法,可以自定义异常处理逻辑。 - 这种方式可以自定义异常处理的策略,例如根据异常类型、请求路径等进行不同的处理。 4. 使用@ControllerAdvice注解和@ModelAttribute注解: - 在全局异常处理类中,可以使用@ModelAttribute注解定义一个方法,用于在异常处理方法执行前,向模型中添加一些通用的属性。 - 这种方式适合在异常处理前,向模型中添加一些额外的信息,以便在异常处理方法中使用。 以上是几种常见的Spring MVC异常处理方式,根据具体的需求和场景,选择适合的方式进行异常处理
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值