spring boot 学习手册
  • 介绍
  • 基础教程
    • 1.RESTfull API简单项目的快速搭建
    • 2.配置文件详解:Properties和YAML
    • 3.配置文件-多环境配置
    • 4.日志配置-logback和log4j2
  • web应用开发
    • 1.模板引擎
    • 2.模板引擎FreeMarker
    • 3.模板引擎Thymeleaf
    • 4.模板引擎jsp
    • 5.错误处理
    • 6.Servlets, Filters, listeners
    • 7.CORS支持
    • 8.文件上传
    • 9.Interceptor拦截器
    • 10.AOP统一处理Web请求日志
    • 11.全局统一异常处理
    • 12. Retry重试
    • 13.RestTemplate
  • 关系型数据库
    • 1.JdbcTemplate
    • 2.Spring-data-jpa
      • @Id 和 @GeneratedValue 详解
      • 配置与注解备注
      • 全局统一前缀策略
      • 映射关系详解
      • 查询、分页、排序
      • JPA 资料
      • 进阶:jpa自定义行为方法
      • 进阶:锁
      • 进阶:Hibernate Validator
    • 3.事务处理
  • NoSQL数据库
    • 1.Redis
    • 2.Mongodb
  • Cache
    • 1.EhCache
    • 2.Redis
  • 异步消息服务
    • 1.JMS(ActiveMQ)
    • 2.AMQP(RabbitMQ)
  • Mybatis
    • Mybatis 初使用
    • Mybatis环境搭建
    • Mybatis开发流程
    • 业务开发流程
    • Mybatis资料
  • 进阶
    • 1.调用REST服务-使用代理
    • 2.发送邮件
    • 3.Spring Session实现集群-redis
    • 4.如何进行远程调试
    • 5.生产准备-基于HTTP的监控
    • 6.Spring Boot集成mybatis
    • 7.Spring Boot集成Druid
    • 8.Spring Boot集成Swagger
    • 9.生产部署-注意事项和如何使用脚本
  • 升华
    • Jenkins部署Spring Boot
    • 异步处理Http请求
    • FastDFS
    • Docker
    • 定时任务(corn job)
    • 批处理
    • @Async实现异步调用
  • 单元测试
    • WireMock伪造服务
  • 安全
    • 1.Spring Security
      • 认证
    • 2.Apache Shiro
  • TaskExecutor 异步线程池
  • 其他
    • 1.修改启动时显示
    • 2.获取配置文件中的值
    • 3.嵌入式容器
    • 4.配置SSL
    • 5.websocket
    • 6.Spring IO Platform
  • RESTfull API 开发
  • 附录:Eclipse - Spring Tool Suite工具的安装
  • 附录:Eclipse部署Maven
  • 附录:SpringBoot相关模块
  • 附录:注解笔记
  • 资料
  • 开发技巧
  • maven插件
Powered by GitBook
On this page
  • 一.错误的处理
  • 方法一:Spring Boot 将所有的错误默认映射到/error, 实现
  • 方法二:添加自定义的错误页面
  • 方法三:使用注解@ControllerAdvice

Was this helpful?

  1. web应用开发

5.错误处理

Previous4.模板引擎jspNext6.Servlets, Filters, listeners

Last updated 5 years ago

Was this helpful?

均在模板引擎FreeMarker下测试

一.错误的处理

方法一:Spring Boot 将所有的错误默认映射到/error, 实现

①BaseErrorController

package com.demotm.example.controller;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.error.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();
    }

}

②创建error模板error.ftl

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

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

  • 2.1 html静态页面:在resources/public/error/ 下定义

    如添加404页面: resources/public/error/404.html页面,中文注意页面编码

  • 2.2 模板引擎页面:在templates/error/下定义

    如添加5xx页面: templates/error/5xx.ftl

    注:templates/error/ 这个的优先级比较 resources/public/error/高

src\main\resources\templates\error\5xx.ftl

<!DOCTYPE html>
<html>
<head lang="en">
    <title>Spring Boot Demo - FreeMarker</title>
</head>
<body>
    <h1>5xx-系统错误</h1>
    <h1>${exception}</h1>
</body>
</html>

controller中加入

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

方法三:使用注解@ControllerAdvice

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

实例:

ErrorExceptionHandler

package com.demotm.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;

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

    private static final Logger logger = LoggerFactory.getLogger(ErrorExceptionHandler.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("roncooException", 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("roncooException", exception.getMessage());
        m.setViewName("error/500");
        return m;
    }

}

src\main\resources\templates\error\500.ftl

<!DOCTYPE html>
<html>
<head lang="en">
    <title>Spring Boot Demo - FreeMarker</title>
</head>
<body>
    <h1>500-系统错误</h1>
    <h1>${exception}</h1>
</body>
</html>

备注当Rest风格情况下返回的json,可以参考以下写法

@RestControllerAdvice
public class ExceptionHandlerController {

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.OK)
    public Map<String, Object> handleException(RuntimeException exception) {

        Map<String, Object> result = new HashMap<>();
        result.put("result", "fail");
        result.put("errMsg", exception.getMessage());

        return result;
    }


}