温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在SpringMVC中对全局异常进行处理

发布时间:2021-01-13 14:05:16 来源:亿速云 阅读:188 作者:Leah 栏目:开发技术

怎么在SpringMVC中对全局异常进行处理?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

SpringMVC全局异常处理的三种方式

  • 使用 Spring MVC 提供的简单异常处理器 SimpleMappingExceptionResolver;

  • 实现 Spring 的异常处理接口 HandlerExceptionResolver 自定义自己的异常处理器;

  • 使用 @ExceptionHandler 注解实现异常处理;

案例实操

全局异常处理方式一

配置 SimpleMappingExceptionResolver 对象

<bean class="org.springframework.web.servlet.handler.SimpleMappingException Resolver">
  <property name="defaultErrorView" value="error"></property>
  <property name="exceptionAttribute" value="ex"></property>
  <property name="exceptionMappings">
    <props>
      <prop key="com.xxx.exception.BusinessException">error1</prop>
      <prop key="com.xxx.exception.ParamsException">error2</prop>
    </props>
  </property>
</bean>

全局异常处理方式二

实现 HandlerExceptionResolver 接口

@Component
public class GlobalException implements HandlerExceptionResolver {
  @Override
  public ModelAndView resolveException(HttpServletRequest request,
    HttpServletResponse response, Object handler, Exception ex) {
      Map<String,Object> map=new HashMap<String, Object>();
      map.put("ex", ex);
      ModelAndView mv=null;
      if(ex instanceof ParamsException){
      	return new ModelAndView("error_param", map);
      }
      if(ex instanceof BusinessException){
      	return new ModelAndView("error_business", map);
      }
    return new ModelAndView("error", map);
  } 
}

使用实现 HandlerExceptionResolver 接口的异常处理器进行异常处理,具有集成简单、有良好的扩展性、对已有代码没有入侵性等优点,同时,在异常处理时能获取导致出现异常的对象,有利于提供更详细的异常处理信息。

全局异常处理方式三

页面处理器继承 BaseController

public class BaseController {
  @ExceptionHandler
  public String exc(HttpServletRequest request,HttpServletResponse
  response,Exception ex){
    request.setAttribute("ex", ex);
    if(ex instanceof ParamsException){
      return "error_param"; 
    }
    if(ex instanceof BusinessException){
      return "error_business"; 
    }
    return "error";
  } 
}

使用 @ExceptionHandler 注解实现异常处理,具有集成简单、有扩展性好(只需要将要异常处理的 Controller 类继承于 BaseController 即可)、不需要附加 Spring 配置等优点,但该方法对已有代码存在入侵性(需要修改已有代码,使相关类继承于 BaseController),在异常处理时不能获取除异常以外的数据。

看完上述内容,你们掌握怎么在SpringMVC中对全局异常进行处理的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI