码迷,mamicode.com
首页 > 编程语言 > 详细

Spring Boot Sample 015之spring-boot-error-exception

时间:2020-06-08 12:41:39      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:mat   public   asi   lan   package   12c   添加文件   lte   demo   

一、环境

  • Idea 2020.1
  • JDK 1.8
  • maven

二、目的

spring boot 统一异常处理实现。

三、步骤

3.1、点击File -> New Project -> Spring Initializer,点击next

技术图片

3.2、在对应地方修改自己的项目信息

技术图片

3.3、选择Web依赖,选中Spring Web。可以选择Spring Boot版本,本次默认为2.2.6,点击Next

技术图片

3.4、项目结构

技术图片

四、添加文件

技术图片

pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<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 https://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>2.2.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>org.ouyushan</groupId>
    <artifactId>spring-boot-error-exception</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-error-exception</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.5.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

添加index.ftl

<!DOCTYPE html>
<html>
<head lang="en">
    <title>Spring Boot Demo - FreeMarker</title>

    <link href="/css/index.css" rel="stylesheet" />

</head>
<body>
<div style="text-align: center;">
    <img src="/images/springboot.jpg" />
    <h1 id="title">${title}</h1>
</div>

<script type="text/javascript" src="/webjars/jquery/3.5.0/jquery.min.js"></script>

<script>
    $(function(){
        $(‘#title‘).click(function(){
            alert(‘点击了‘);
        });
    })
</script>
</body>
</html>

 

500.ftl
<!DOCTYPE html>
<html>
<head lang="en">
    <title>Spring Boot Demo - FreeMarker</title>
</head>
<body>
<h1>500-${exception}</h1>
<h1>${author}</h1>
</body>
</html>
添加index.css
h1{color: blue;}
配置文件application.properties
spring.freemarker.template-loader-path=classpath:/templates
spring.freemarker.suffix=.ftl

 

UserController.java
package org.ouyushan.springboot.error.exception.controller;

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

/**
 * @Description:
 * @Author: ouyushan
 * @Email: ouyushan@hotmail.com
 * @Date: 2020/5/7 14:41
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/index")
    public String index(ModelMap map){
        map.put("title", "freemarker hello word");
        return "index"; // 开头不要加上/,linux下面会出错
    }

    @RequestMapping(value = "/runtimeException")
    public String runtimeException(ModelMap map) {
        throw new RuntimeException("测试异常");
    }

    @RequestMapping(value = "/error")
    public String error(ModelMap map) throws Exception {
        throw new Exception("测试错误");
    }
}

 

ErrorExceptionHandler.java
package org.ouyushan.springboot.error.exception.handler;

/**
 * @Description:
 * @Author: ouyushan
 * @Email: ouyushan@hotmail.com
 * @Date: 2020/5/7 14:44
 */

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * 异常处理
 */
@ControllerAdvice
public class ErrorExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(ErrorExceptionHandler.class);

    /**
     * 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
    }

    /**
     * 把值绑定到Model中,使全局@RequestMapping可以获取到该值
     * @param model
     */
    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("author", "ouyushan");
    }

    /**
     * 统一异常处理
     *
     * @param exception
     *
     * @return
     */

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.OK)
    public ModelAndView processException(RuntimeException exception) {
        logger.info("自定义异常处理-RuntimeException");
        ModelAndView m = new ModelAndView();
        logger.info("--------------------" + exception.getMessage());
        m.addObject("author", "ouyushan");
        m.addObject("exception", "runtimeException");
        m.setViewName("error/500");
        return m;
    }

    /**
     * 统一异常处理
     *
     * @param exception
     *
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public ModelAndView processException(Exception exception) {
        logger.info("自定义异常处理-Exception");
        ModelAndView m = new ModelAndView();
        logger.info("--------------------" + exception.getMessage());
        m.addObject("author", "ouyushan");
        m.addObject("exception", "exception");
        m.setViewName("error/500");
        return m;
    }

}

五、测试

请求:
返回:
500-exception
ouyushan

请求:

返回:
500-runtimeException
ouyushan

 

Spring Boot Sample 015之spring-boot-error-exception

标签:mat   public   asi   lan   package   12c   添加文件   lte   demo   

原文地址:https://www.cnblogs.com/ouyushan/p/13064711.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!