1.添加Maven依赖

<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>top.ytheng</groupId>
<artifactId>springboot-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</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-thymeleaf</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<scope>true</scope>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

2.添加自定义异常类

package top.ytheng.demo.domain;

public class MyException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public MyException(String code, String msg) {
this.code = code;
this.msg = msg;
} private String code;
private String msg; public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
} }

3.添加异常处理类

package top.ytheng.demo.domain;

import java.util.HashMap;
import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView; //如果返回的是Json格式的数据,
//可以使用@ResponseBody+@ControllerAdvice替换@RestControllerAdvice
@RestControllerAdvice
//@ControllerAdvice
public class CustomExtHandler {
private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class); //捕获全局异常,处理所有不可知的异常
@ExceptionHandler(value=Exception.class)
//@ResponseBody
public Object handleException(Exception e, HttpServletRequest request) {
LOG.error("msg:{},url:{}", e.getMessage(), request.getRequestURL()); Map<String, Object> map = new HashMap<>();
map.put("code", 100);
map.put("msg", e.getMessage());
map.put("url", request.getRequestURL());
return map;
} //自定义异常
//需要添加thymeleaf依赖
//路径:src/main/resources/templates/error.html
@ExceptionHandler(value=MyException.class)
public Object handleMyException(MyException e, HttpServletRequest request) {
//返回Json数据,由前端进行界面跳转
//Map<String, Object> map = new HashMap<>();
//map.put("code", e.getCode());
//map.put("msg", e.getMsg());
//map.put("url", request.getRequestURL());
//return map; //进行页面跳转
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error.html");
modelAndView.addObject("msg", e.getMsg());
return modelAndView;
}
}

4.添加异常控制器

package top.ytheng.demo.controller;

import java.util.HashMap;
import java.util.Map; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import top.ytheng.demo.domain.MyException; @RestController
@RequestMapping("/exce")
public class ExceptionController { @RequestMapping("/api/v1/exce")
public Object testException() {
Map<String, Object> map = new HashMap<>();
map.put("name", "ytheng");
map.put("pwd", 123456); int data = 1/0;
return map;
} @RequestMapping("/api/v1/myexce")
public Object testMyException() { throw new MyException("500", "my ext异常"); }
}

5.添加启动类

package top.ytheng.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication //等于下面3个
//@SpringBootConfiguration
//@EnableAutoConfiguration
//@ComponentScan
public class DemoApplication { public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
} }

6.添加文件配置application.properties

#端口号
server.port=8090 #当前项目根目录下创建爱你日志文件
logging.file=C:\\Users\\tianheng\\eclipse-workspace\\springboot.log

7.添加error.html界面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>错误信息界面</h1>
</body>
</html>

8.右键Run As启动项目,访问地址

http://localhost:8090/exce/api/v1/exce
http://localhost:8090/exce/api/v1/myexce

另附:

SpringBoot------全局异常捕获和自定义异常的更多相关文章

  1. springboot 全局异常捕获,异常流处理业务逻辑

    前言 上一篇文章说到,参数校验,往往需要和全局的异常拦截器来配套使用,使得返回的数据结构永远是保持一致的.参数异常springboot默认的返回结构: { "timestamp": ...

  2. springBoot 全局异常方式处理自定义异常 @RestControllerAdvice + @ExceptionHandler

    前言 本文讲解使用 @ControllerAdvice + @ExceptionHandler 进行全局的 Controller 层异常处理,可以处理大部分开发中用到的自自定义业务异常处理了,再也不用 ...

  3. Spring boot异常统一处理方法:@ControllerAdvice注解的使用、全局异常捕获、自定义异常捕获

    一.全局异常 1.首先创建异常处理包和类 2.使用@ControllerAdvice注解,全局捕获异常类,只要作用在@RequestMapping上,所有的异常都会被捕获 package com.ex ...

  4. SpringBoot全局异常拦截

    SpringBoot全局异常捕获 使用到的技能 @RestControllerAdvice或(@ControllerAdvice+@ResponseBody) @ExceptionHandler 代码 ...

  5. 【快学springboot】5.全局异常捕获,异常流处理业务逻辑

    前言 上一篇文章说到,参数校验,往往需要和全局的异常拦截器来配套使用,使得返回的数据结构永远是保持一致的.参数异常springboot默认的返回结构: { "timestamp": ...

  6. SpringBoot图文教程15—项目异常怎么办?「跳转404错误页面」「全局异常捕获」

    有天上飞的概念,就要有落地的实现 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例都敲一遍 先赞后看,养成习惯 SpringBoot 图文教程系列文章目录 SpringBoot图文教程1-Spr ...

  7. springboot(二 如何访问静态资源和使用模板引擎,以及 全局异常捕获)

    在我们开发Web应用的时候,需要引用大量的js.css.图片等静态资源. 默认配置 Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则: /static / ...

  8. springboot编程之全局异常捕获

    springboot编程之全局异常捕获 1.创建GlobalExceptionHandler.java,在类上注解@ControllerAdvice, 在方法上注解@ExceptionHandler( ...

  9. SpringBoot 全局异常拦截捕获处理

    一.全局异常处理 //Result定义全局数据返回对象 package com.xiaobing.demo001.domain; public class Result { private Integ ...

  10. 测试开发专题:spring-boot统一异常捕获

    java异常介绍 异常时相对于return的一种退出机制,可以由系统触发,也可由程序通过throw语句触发,异常可以通过try/catch语句进行捕获并处理,如果没有捕获,则会导致程序退出并输出异常栈 ...

随机推荐

  1. MAC自动脚本

    链接: crontab 详细用法 定时任务 Linux crontab命令 定时任务 用法详解以及no crontab for root解决办法

  2. Linux命令Find实例

    转自: http://www.tecmint.com/35-practical-examples-of-linux-find-command/ 35 Practical Examples of Lin ...

  3. Jenkins配置基于角色的项目权限管理

    转自: http://www.cnblogs.com/gao241/archive/2013/03/20/2971416.html, 版权归原作者. 本文将介绍如何配置jenkins,使其可以支持基于 ...

  4. python 路径和文件的遍历

    python发现文件夹下所有的jpg文件,并且安装文件排放的顺序输出 glob模块是最简单的模块之一,内容非常少.用它可以查找符合特定规则的文件路径名.跟使用windows下的文件搜索差不多.查找文件 ...

  5. 从入门到精通Puppet的实践之路

    本文有感于<精通Puppet配置管理工具>在豆瓣上的某些差评而顺手写的书评. 半路出家   故事要从12年初说起.  某天,部门老大让我所在team的老大调研一下当下业界的配置管理工具.于 ...

  6. 【ShoppingPeeker】-基于Webkit内核的爬虫蜘蛛引擎 ShoppingWebCrawler的姊妹篇-可视化任务Web管理

    ShoppingPeeker 这个项目是蜘蛛项目的可视化任务站点. 项目github地址:ShoppingPeeker 开发语言:C# 开发工具:Visual Studio 2017 +.Net Co ...

  7. 让 Python 更加充分的使用 Sqlite3

    我最近在涉及大量数据处理的项目中频繁使用 sqlite3.我最初的尝试根本不涉及任何数据库,所有的数据都将保存在内存中,包括字典查找.迭代和条件等查询.这很好,但可以放入内存的只有那么多,并且将数据从 ...

  8. http头文件User-Agent详解【转载】

    原文地址:http://blog.csdn.net/andybbc/article/details/50587359 http头文件User-Agent详解 什么是User-Agent User-Ag ...

  9. 你被R语言的=和<-搞昏了头吗

    学习R有一周了,心中一直有一个困惑,关于= 和 <-,今晚决定搞定它! 迄今为止用到最多的函数是matrix() 和c(),就用他们说起!   之前学了四五门语言,对于=赋值已经成了惯性,下面是 ...

  10. SNF开发平台WinForm-表单验证控件-通用

    CS程序也能做到像BS程序一样的验证效果,如下: 1.验证控件的展示 校验时如果不符合验证条件的控件,会在控件上显示较显眼的图标. 当出现不符合验证的控件时,鼠标悬浮会显示自定义的提示信息. 如:输入 ...