zoukankan      html  css  js  c++  java
  • Spring MVC 处理异常

    SpringMVC处理异常:

      1 使用@ExceptionHandler注解

        只有ModelAndView可以携带错误信息

        @ExceptionHandler
        public ModelAndView handleException(Exception ex) {
    System.out.println(
    "出现异常:" + ex);
    ModelAndView mv
    = new ModelAndView(); mv.setViewName("error");//转到error.jsp mv.addObject("exception", ex);
    return mv; }
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8" isErrorPage="true"%>
    
    <!-- 打印异常信息 -->
    <%=exception.getMessage() %>
    ${exception.message}

      2 使用@ExceptionHandler处理特定类型的异常

    public class LackParamException extends ServletException{
       
      
    private static final long serialVersionUID = 1L;
      
    public LackParamException() { super("缺少参数"); } public LackParamException(String msg) { super(msg); } }
        @ExceptionHandler(LackParamException.class)
        public ModelAndView handleException(Exception ex) {
            System.out.println("出现异常:" + ex);
            ModelAndView mv = new ModelAndView();
            mv.setViewName("error");
            mv.addObject("exception", ex);
            return mv;
        }
        
        @RequestMapping("test_exception")
        public String testException(String str) throws LackParamException {
            if(StringUtils.isEmpty(str)) {
                throw new LackParamException();
            }
            return "success";
        }

      3 使用@ControllerAdvice织入全局异常

    //异常切面:将本类内部的@ExceptionHandler方法织入到所有的@RequestMapping方法
    @ControllerAdvice
    public class MyExceptionHandler {
    @ExceptionHandler(Exception.
    class) public ModelAndView handleException(Exception ex) { System.out.println("出现全局异常:" + ex); ModelAndView mv = new ModelAndView(); mv.setViewName("error"); mv.addObject("exception", ex); return mv; } }
     <!-- 扫描异常处理 -->
     <context:component-scan base-package="com.roxy.springmvc.exception">
    </context:component-scan>
  • 相关阅读:
    会议安排最优算法
    Python Singleton
    Android HandlerThread 源代码分析
    [Android]_[0基础]_[adb 有用命令]
    使用sshfs将远程目录挂载到本地
    Netty 中ChannelOption的含义以及使用的场景
    netty4.0 Server和Client的通信
    Netty重要概念介绍
    Zookeeper单机伪集群
    整数集合
  • 原文地址:https://www.cnblogs.com/roxy/p/7604030.html
Copyright © 2011-2022 走看看