Unified management of exceptions

1. Custom exception

就是我们自己重新定义一个异常类,继承runtimeException
public class UserNameAlreadyExistsException  extends RuntimeException{
  private static final long serialVersionUID = 1L;

  public UserNameAlreadyExistsException(String message) {
      super(message);
}

2. Determine whether there is an abnormality

    //2.检查用户名是否被占用
    int  count = userMapper.getUserCount (userName);
    //3.如果被占用则抛出自定义异常
    if (count>0) {
        throw new UserNameAlreadyExistsException(GlobaleMessage.USERNAME_ALREADYEXISTS);
    }

3. Define constants in the GlobaleMessage class

public class GlobaleMessage {
    public static final String USERNAME_ALREADYEXISTS = "用户名已存在,请重新注册!";

}

4. Configure in the MVC file

<!-- 配置ExceptionMapping统一管理项目中的异常 -->
<bean id="simpleMappingExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <!-- key属性:异常全类名,“开始和结束标签之间部分”:捕获到异常后要前往的逻辑视图名称 -->
            <prop key="com.atguigu.survey.e.UserNameAlreadyExistsException">guest/user_registUI</prop>
        </props>
    </property>
</bean>

5. Take out the exception message on the page

SpringMVC捕获到异常后,会将异常对象保存到请求域中,属性名是exception
在页面上使用下面的EL表达式就可以取出异常信息
<c:if test="${requestScope.exception != null }">
            <div class="text-center">${requestScope.exception.message }</div>
        </c:if>

6. Meaning

这个机制建立起来后,可以在各个不同模块中都是用相同的办法显示错误消息

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325441695&siteId=291194637