springBoot异常统一处理

采用@ControllerAdvice注解和@ExceptionHandler注解,可以对异常进行统一处理。

1.结构图:

2.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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.didispace</groupId>
<artifactId>Chapter3-1-6</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging> <name>Chapter3-1-6</name>
<description>Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> </dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build> </project>

3.配置文件:

server.port=9000

4.index.html

<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<h1 th:text="${host}">Hello World</h1>
</body>
</html>

5.error.html

<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head lang="en">
<meta charset="UTF-8" />
<title>统一异常处理</title>
</head>
<body>
<h1>Error Handler</h1>
<div th:text="${url}"></div>
<div th:text="${exception.message}"></div>
</body>
</html>

6.ErrorInfo

package com.didispace.dto;

public class ErrorInfo<T> {

    public static final Integer OK = 0;
public static final Integer ERROR = 100; private Integer code;
private String message;
private String url;
private T data; public String getUrl() {
return url;
} public void setUrl(String url) {
this.url = url;
} public static Integer getOK() {
return OK;
} public static Integer getERROR() {
return ERROR;
} public Integer getCode() {
return code;
} public void setCode(Integer code) {
this.code = code;
} public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} public T getData() {
return data;
} public void setData(T data) {
this.data = data;
} }

7.myExecption:

package com.didispace.exception;

/**
* @author 程序猿DD
* @version 1.0.0
* @date 16/5/2 上午10:50.
* @blog http://blog.didispace.com
*/
public class MyException extends Exception { public MyException(String message) {
super(message);
} }

8.GlobalExceptionHandler:

package com.didispace.exception;

import com.didispace.dto.ErrorInfo;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; @ControllerAdvice
public class GlobalExceptionHandler { @ExceptionHandler(value = Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("url", req.getRequestURL());
mav.setViewName("error");
return mav;
} @ExceptionHandler(value = MyException.class)
@ResponseBody
public ErrorInfo<String> jsonErrorHandler(HttpServletRequest req, MyException e) throws Exception {
ErrorInfo<String> r = new ErrorInfo<>();
r.setMessage(e.getMessage());
r.setCode(ErrorInfo.ERROR);
r.setData("Some Data");
r.setUrl(req.getRequestURL().toString());
return r;
} }

9.启动项:

package com.didispace;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; /**
*
* @author 程序猿DD
* @version 1.0.0
* @blog http://blog.didispace.com
*
*/
@SpringBootApplication
public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }

10.controller:

package com.didispace.web;

import com.didispace.exception.MyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; /**
*
* @author 程序猿DD
* @version 1.0.0
* @blog http://blog.didispace.com
*
*/
@Controller
public class HelloController { @RequestMapping("/hello")
public String hello() throws Exception {
throw new Exception("发生错误");
} @RequestMapping("/json")
public String json() throws MyException {
throw new MyException("发生错误2");
} @RequestMapping("/")
public String index(ModelMap map) {
map.addAttribute("host", "http://blog.didispace.com");
return "index";
} }

11.访问url:

http://localhost:9000/hello               

http://localhost:9000/json               

http://localhost:9000/                     

springBoot异常统一处理的更多相关文章

  1. springboot学习-jdbc操作数据库--yml注意事项--controller接受参数以及参数校验--异常统一管理以及aop的使用---整合mybatis---swagger2构建api文档---jpa访问数据库及page进行分页---整合redis---定时任务

    springboot学习-jdbc操作数据库--yml注意事项--controller接受参数以及参数校验-- 异常统一管理以及aop的使用---整合mybatis---swagger2构建api文档 ...

  2. Springboot项目全局异常统一处理

    转自https://blog.csdn.net/hao_kkkkk/article/details/80538955 最近在做项目时需要对异常进行全局统一处理,主要是一些分类入库以及记录日志等,因为项 ...

  3. SpringBoot异常处理统一封装我来做-使用篇

    SpringBoot异常处理统一封装我来做-使用篇 简介 重复功能我来写.在 SpringBoot 项目里都有全局异常处理以及返回包装等,返回前端是带上succ.code.msg.data等字段.单个 ...

  4. springboot返回统一接口与统一异常处理

    springboot返回统一接口与统一异常处理 编写人员:yls 编写时间:2019-9-19 0001-springboot返回统一接口与统一异常处理 简介 创建统一的返回格式 Result 封装统 ...

  5. Springboot项目统一异常处理

    Springboot项目统一异常处理 一.接口返回值封装 1. 定义Result对象,作为通用返回结果封装 2. 定义CodeMsg对象,作为通用状态码和消息封装 二.定义全局异常类 三.定义异常处理 ...

  6. 深度分析:SpringBoot异常捕获与封装处理,看完你学会了吗?

    SpringBoot异常处理 简介 ​ 日常开发过程中,难免有的程序会因为某些原因抛出异常,而这些异常一般都是利用try ,catch的方式处理异常或者throw,throws的方式抛出异常不管.这种 ...

  7. SpringBoot 如何统一后端返回格式?老鸟们都是这样玩的!

    大家好,我是飘渺. 今天我们来聊一聊在基于SpringBoot前后端分离开发模式下,如何友好的返回统一的标准格式以及如何优雅的处理全局异常. 首先我们来看看为什么要返回统一的标准格式? 为什么要对Sp ...

  8. SpringBoot 如何统一后端返回格式

    在前后端分离的项目中后端返回的格式一定要友好,不然会对前端的开发人员带来很多的工作量.那么SpringBoot如何做到统一的后端返回格式呢?今天我们一起来看看. 为什么要对SpringBoot返回统一 ...

  9. Ext.net 异常统一管理,铥掉可恶的 Request Failure

    Ext.net 异常统一管理,铥掉可恶的 Request Failure 看着这样的框框是不是很不爽 灭他.也不难.. .如果全部页面都有继承一个自定义的父类 ..那整个项目代码量就只有几行了.. 单 ...

随机推荐

  1. [NUnit]No results

    Results (nunit3) saved as TestResult.xmlCommitting...No results, this could be for a number of reaso ...

  2. java并发编程(二)----创建并运行java线程

    实现线程的两种方式 上一节我们了解了关于线程的一些基本知识,下面我们正式进入多线程的实现环节.实现线程常用的有两种方式,一种是继承Thread类,一种是实现Runnable接口.当然还有第三种方式,那 ...

  3. Redis回顾

    之前有两篇文章着重介绍了redis集群的搭建和redis与spring的整合,一个月过去了,现在有些忘记了,今天又拿过来稳固一下,发现有很多的东西都忘记了. 资料汇总下载 首先安装ruby环境 安装过 ...

  4. SpringBoot第二十三篇:安全性之Spring Security

    作者:追梦1819 原文:https://www.cnblogs.com/yanfei1819/p/11350255.html 版权声明:本文为博主原创文章,转载请附上博文链接! 引言   系统的安全 ...

  5. 7.26 面向对象_封装_property_接口

    封装 封装 就是隐藏内部实现细节, 将复杂的,丑陋的,隐私的细节隐藏到内部,对外提供简单的访问接口 为什么要封装 1.保证关键数据的安全性 2.对外部隐藏实现细节,隔离复杂度 什么时候应该封装 1.当 ...

  6. Windows Server 2008在网络环境配置打印机

    下面学习在Windows Server2008在网络环境搭建打印机服务器,打印机服务器也是很常用的,特别是在中大型企业里面,打印机数量比较多为方便管理,可以搭建一个打印机服务,这里介绍一下,本地打印机 ...

  7. Django上线部署之Apache

    环境: 1.Windows Server 2016 Datacenter 64位 2.SQL Server 2016 Enterprise 64位 3.Python 3.6.0 64位 4.admin ...

  8. word编辑visio文件

    Word文档中插入visio文件并编辑: (1)插入->对象->对象->选择“visio文件”,此种方式可插入visio文件的全部. (2)直接打开visio文件->ctrl+ ...

  9. **p,*p和&p使用有感

    *p两种使用情况: 1.定义指针变量,如char *p:这里p是一个变量,单单在这一点上与int a 无差别:但p这个变量特殊在其中只能存地址. 引申:对于char **p,p中存一个地址add1,a ...

  10. Freemarker提供了3种加载模板目录的方法

    Freemarker提供了3种加载模板目录的方法 原创 2016年08月24日 14:50:13 标签: freemarker / Configuration 8197 Freemarker提供了3种 ...