Spring Boot Learning(错误处理)

三种方式:

第一种:

Spring Boot 将所有的错误默认映射到/error, 实现ErrorController

这时候需要定义一个Controller去实现ErrorController

package com.example.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value = "error")
public class BaseErrorController implements ErrorController {
private static final Logger logger = LoggerFactory.getLogger(BaseErrorController.class);

    @Override
    public String getErrorPath() {
        logger.info("出错啦!进入自定义错误控制器");
        return "error/error";
    }

    @RequestMapping
    public String error() {
        return getErrorPath();
    }

}

同时在resource/templates下新建error目录并添加error.ftl,这样在异常发生时就会显示error.ftl页面。

<!DOCTYPE html>
<html>
<head lang="en">
    <title>Spring Boot Demo - FreeMarker</title>
</head>
<body>
    <h1>error-系统出错,请联系后台管理员</h1>
</body>
</html>

代码目录结构:

方法二:添加自定义的错误页面

1 html静态页面:在resources/public/error/ 下定义
如添加404页面: resources/public/error/404.html页面,中文注意页面编码

2 模板引擎页面:在templates/error/下定义
如添加5xx页面: templates/error/5xx.ftl

注:templates/error/ 这个的优先级比较 resources/public/error/高,也就是说如果templates下面如果有相应的异常处理页面会显示它的而不会显示error目录下的页面。

我们去掉刚才写的ErrorController类,同时在WebController类中制造一个异常用于测试。

package com.example.controller;

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

@Controller
@RequestMapping(value = "/web")
public class WebController {

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

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

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

添加404.html和5xx.ftl

5xx.ftl:

<!DOCTYPE html>
<html>
<head lang="en">
    <title>Spring Boot Demo - FreeMarker</title>
</head>
<body>
    <h1>5xx error-系统出错,请联系后台管理员</h1>
    <h1>异常信息:${exception}</h1>
</body>
</html>

方法三:使用注解@ControllerAdvice

自定义一个异常处理类,在该类中可以使用注解拦截异常,可以针对不同异常采取不同处理方式

代码:

package com.example.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class BizExceptionHandler {

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

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

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

}

在templates/error下新建错误页面500.ftl

<!DOCTYPE html>
<html>
<head lang="en">
    <title>Spring Boot Demo - FreeMarker</title>
</head>
<body>
    <h1>500 error-系统出错,请联系后台管理员</h1>
    <h1>异常信息:${ericException}</h1>
</body>
</html>

代码结构:

这三种方式根据需要自行选择,建议使用第三种,更加灵活。

时间: 2024-08-02 19:26:07

Spring Boot Learning(错误处理)的相关文章

Spring Boot 请求错误处理

方法一:Spring Boot将所有的错误映射到/error,实现ErrorController接口 1 @Controller 2 @RequestMapping("/error") 3 public class BaseErrorController implements ErrorController { 4 private final Logger logger = LoggerFactory.getLogger(BaseErrorController.class); 5 6

Spring Boot 常规错误一览及解决方案

更新信息 2016-03-13 开贴 想法很单纯,将自己在Spring Boot学习过程中遇到的各种麻烦列出来,并提供解决方案待查. 正题开始,遇到错误可通过报错信息对号入座: 错误提示:java.net.BindException: Address already in use: bind 推测原因:一开始接触Spring Boot时很常见的错误,端口已绑定.之前已启动Application,Spring Boot会启动内嵌的Tomcat,并绑定端口8080启动前端服务.作为Web应用,程序自

Spring Boot自定义错误页面,Whitelabel Error Page处理方式

我已经是Spring Framework框架的忠实粉丝.对于企业软件开发者来说它提供了对常见问题的通用解决方案,包括那些你在未来开发中没有意识到的问题.但是,它构建的J2EE项目变得比较臃肿,需要被一种新的解决方案替代. 我最大的抱怨就是最开始使用spring Framework构建项目十分缓慢和复杂,比如构建一个包含JPA的MVC应用.为改变这种情况,Spring Boot应运而生了. Spring Boot以一种新的微服务的方式来替代以Spring Framework构建项目的传统方式,我已

spring boot 新手错误

使用模版的时候,出错:Putting a context variable with name "param" is forbidden model.addAttribute("param", "hello,spring boot thymeleaf"); 规定了关键字,param不能作为参数传递出去: model.addAttribute("paraddd", "hello,spring boot thymelea

Spring Boot Learning(配置文件)

Properties配置 配置文件的生效顺序,会对值进行覆盖: 1. @TestPropertySource 注解2. 命令行参数3. Java系统属性(System.getProperties())4. 操作系统环境变量5. 只有在random.*里包含的属性会产生一个RandomValuePropertySource6. 在打包的jar外的应用程序配置文件(application.properties,包含YAML和profile变量)7. 在打包的jar内的应用程序配置文件(applica

Spring Boot Learning(日志配置)

支持日志框架:Java Util Logging, Log4J2 and Logback,默认是使用logback配置方式:默认配置文件配置和引用外部配置文件配置 一. 默认配置文件配置(不建议使用:不够灵活,对log4j2等不够友好)# 日志文件名,比如:roncoo.log,或者是 /var/log/roncoo.loglogging.file=roncoo.log # 日志级别配置,比如: logging.level.org.springframework=DEBUGlogging.lev

Spring Boot Learning(helloWorld)

使用 Spring Tool Suite 工具开发,注意和eclipse版本的队员. 步骤: 最后生成的目录结构: 在这里我们可以通过查看pom.xml看看都有哪些包被依赖了进去: 可以看到,当在前面建立工程的时候选择web,默认回引入内置的tomcat. 接下来,代码: package com.example.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springf

Spring Boot Learning(配置文件--多环境配置)

多环境配置的好处: 1.不同环境配置可以配置不同的参数2.便于部署,提高效率,减少出错 Properties多环境配置 1. 配置激活选项    spring.profiles.active=dev2.添加其他配置文件 application-test.properties application-dev.properties application-prod.properties Yaml多环境配置: 1.配置激活选项  spring:    profiles:      active: de

spring boot 常见错误解决

1.报此错误:2017-06-07 09:02:44.308 ERROR 340 --- [et_localhost-19] c.n.e.cluster.ReplicationTaskProcessor : Batch update failure with HTTP status code 401; discarding 1 replication tasks 检查是否配置 (要检查 eureka -server 而不是 client) eureka: instance: hostname: