Springboot--Exception

Posted 周无极

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot--Exception相关的知识,希望对你有一定的参考价值。

                           Springboot--Exception 自定义异常类

 

package com.bjsxt.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * SpringBoot处理异常方式一:自定义错误页面
 *
 *
 */
@Controller
public class DemoController {
    
    @RequestMapping("/show")
    public String showInfo(){
        String str = null;
        str.length();
        return "index";
    }
    
    @RequestMapping("/show2")
    public String showInfo2(){
        int a = 10/0;
        return "index";
    }
    
    
}
DemoController
package com.bjsxt.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class UsersController {

    @RequestMapping("/showUsers")
    public String showUser(){
        String str = null;
        str.length();
        return "index";
    }
    
    @RequestMapping("/showUsers2")
    public String showUser2(){
        int a = 100/0;
        return "index";
    }
}
UsersController
package com.bjsxt.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

/**
 * 全局异常处理类
 *
 *
 */
@ControllerAdvice
public class GlobalException {
    /**
     * java.lang.ArithmeticException
     * 该方法需要返回一个ModelAndView:目的是可以让我们封装异常信息以及视图的指定
     * 参数Exception e:会将产生异常对象注入到方法中
     */
    @ExceptionHandler(value={java.lang.ArithmeticException.class})
    public ModelAndView arithmeticExceptionHandler(Exception e){
        ModelAndView mv = new ModelAndView();
        mv.addObject("error", e.toString());
        mv.setViewName("error1");
        return mv;
    }
    
    /**
     * java.lang.NullPointerException
     * 该方法需要返回一个ModelAndView:目的是可以让我们封装异常信息以及视图的指定
     * 参数Exception e:会将产生异常对象注入到方法中
     */
    @ExceptionHandler(value={java.lang.NullPointerException.class})
    public ModelAndView nullPointerExceptionHandler(Exception e){
        ModelAndView mv = new ModelAndView();
        mv.addObject("error", e.toString());
        mv.setViewName("error2");
        return mv;
    }
    
}
GlobalException
package com.bjsxt;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * 
 *SpringBoot处理异常方式一:自定义错误页面
 *
 */
@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
App
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>错误提示页面</title>
</head>
<body>
    出错了,请与管理员联系。。。
    <span th:text="${exception}"></span>
</body>
</html>
error.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>错误提示页面-ArithmeticException</title>
</head>
<body>
    出错了,请与管理员联系。。。
    <span th:text="${error}"></span>
</body>
</html>
error1.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>错误提示页面-NullPointerException</title>
</head>
<body>
    出错了,请与管理员联系。。。
    <span th:text="${error}"></span>
</body>
</html>
error2.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Thymeleaf入门</title>
</head>
<body>
    <span th:text="Hello"></span>
    <hr/>
    <span th:text="${msg} "></span>
    <hr/>
    <input type="text" name="username" th:value="${msg}"/>
    <hr/>
    <span th:text="${#strings.isEmpty(msg)}"></span>
    <hr/>
    <span th:text="${#strings.contains(msg,\'9\')}"></span>
    <span th:text="${#strings.contains(msg,\'T\')}"></span>
    <hr/>
    <span th:text="${#strings.startsWith(msg,\'a\')}"></span>
    <span th:text="${#strings.startsWith(msg,\'T\')}"></span>
    <hr/>
    <span th:text="${#strings.endsWith(msg,\'a\')}"></span>
    <span th:text="${#strings.endsWith(msg,\'案例\')}"></span>
    <hr/>
    <span th:text="${#strings.length(msg)}"></span>
    <hr/>
    <span th:text="${#strings.indexOf(msg,\'h\')}"></span>
    <hr/>
    <span th:text="${#strings.substring(msg,13)}"></span>
    <span th:text="${#strings.substring(msg,13,14)}"></span>
    <hr/>
    <span th:text="${#strings.toUpperCase(msg)}"></span>
    <span th:text="${#strings.toLowerCase(msg)}"></span>
    <hr/>
    <span th:text="${#dates.format(key)}"></span>
    <hr/>
    <span th:text="${#dates.format(key,\'yyy/MM/dd\')}"></span>
    <hr/>
    <span th:text="${#dates.year(key)}"></span>-
    <hr/>
    <span th:text="${#dates.month(key)}"></span>-
    <hr/>
    <span th:text="${#dates.day(key)}"></span>
</body>
</html>
index.html
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.10.RELEASE</version>
  </parent>
  <groupId>com.bjsxt</groupId>
  <artifactId>16-spring-boot-exception3</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <properties>
  <java.version>1.7</java.version>
  <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
  <thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
  </properties>
  
  <dependencies>
      <!-- springBoot的启动器 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- springBoot的启动器 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
  </dependencies>
</project>
pom.xml

 

第二方式

package com.bjsxt.exception;

import java.util.Properties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

/**
 * 通过SimpleMappingExceptionResolver做全局异常处理
 *
 *
 */
@Configuration
public class GlobalException {
    
    /**
     * 该方法必须要有返回值。返回值类型必须是:SimpleMappingExceptionResolver
     */
    @Bean
    public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver(){
        SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
        
        Properties mappings = new Properties();
        
        /**
         * 参数一:异常的类型,注意必须是异常类型的全名
         * 参数二:视图名称
         */
        mappings.put("java.lang.ArithmeticException", "error1");
        mappings.put("java.lang.NullPointerException","error2");
        
        //设置异常与视图映射信息的
        resolver.setExceptionMappings(mappings);
        
        return resolver;
    }
    
}
GlobalException

第三方式

package com.bjsxt.exception;

import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

/**
 * 通过实现HandlerExceptionResolver接口做全局异常处理
 *
 *
 */
@Configuration
public class GlobalException implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
        ModelAndView mv = new ModelAndView();
        //判断不同异常类型,做不同视图跳转
        if(ex instanceof ArithmeticException){
            mv.setViewName("error1");
        }
        
        if(ex instanceof NullPointerException){
            mv.setViewName("error2");
        }
        mv.addObject("error", ex.toString());
        
        return mv;
    }
}
GlobalException

 

以上是关于Springboot--Exception的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot - BeanDefinitionOverrideException:无效的bean定义

微信小程序代码片段

VSCode自定义代码片段——CSS选择器

谷歌浏览器调试jsp 引入代码片段,如何调试代码片段中的js

片段和活动之间的核心区别是啥?哪些代码可以写成片段?

VSCode自定义代码片段——.vue文件的模板