zoukankan      html  css  js  c++  java
  • Spring MVC处理异常有3种方法

    1.使用 SimpleMappingExceptionResolver 实现异常处理

    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <!-- 异常处理页面 -->
        <property name="defaultErrorView" value="error"></property>
        <!-- 异常信息的变量名,默认名为exception -->
        <property name="exceptionAttribute" value="ex"></property>
        <!-- 需要处理的异常 -->
        <property name="exceptionMappings">
            <props>
                <prop key="xxxxException">error-xxx</prop>
                <prop key="yyyyException">error-yyy</prop>
                <prop key="...">...</prop>
            </props>
        </property>
    </bean>

    2.实现HandlerExceptionResolver 接口自定义异常处理器

    public class DefaultExceptionHandler implements HandlerExceptionResolver
    {
    
        @Override
        public ModelAndView resolveException(
                HttpServletRequest request,
                HttpServletResponse response,
                Object o,
                Exception e) {
        
            return new ModelAndView("error");
        }
    }

    3.使用@ControllerAdvice,@ExceptionHandler 注解实现

    @ControllerAdvice
    public class DefaultExceptionHandler
    {
        @ExceptionHandler(Throwable.class)
        public ModelAndView resolveException(Exception ex)
        {
            // FastJsonJsonView
            HashMap<String, Object> map = new HashMap<>();
            map.put("code", "1001");
            map.put("msg", ex.getMessage());
    
            log.error("异常:" + ex.getMessage(), ex);
            return new ModelAndView("error", map);
        }
    }
  • 相关阅读:
    高进度乘法FFT优化
    Activity的四种加载模式
    异步任务AsyncTask
    利用Handler在子线程中更新UI
    Android 屏幕旋转监听
    HDOJ-1698-线段树成段更新
    HDOJ-1671-字典树
    HDOJ-1251 字典树
    python数据结构与算法
    find the lowest number location
  • 原文地址:https://www.cnblogs.com/appleat/p/9100884.html
Copyright © 2011-2022 走看看