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. 使用 IntraWeb (28) - 基本控件之 TIWTemplateProcessorHTML、TIWLayoutMgrHTML、TIWLayoutMgrForm

    TIWTemplateProcessorHTML //使用外部的 html 文件做模板 TIWLayoutMgrHTML //直接输入 Html 文本做模板 TIWLayoutMgrForm //这应 ...

  2. JProfiler远程监控

    1.  服务端安装JProfiler(与客户端版本一致) 2.  客户端配置连接: A).session——integration wizards——New remote integration B) ...

  3. Unity3D游戏制作(三)——移动平台上的角色阴影制作

    本系列文章由 Amazonzx 编写,欢迎转载,转载请注明出处. http://blog.csdn.net/amazonzx/article/details/7973740 本文将重点介绍两种目前在移 ...

  4. App架构师实践指南六之性能优化三

    App架构师实践指南六之性能优化三 2018年08月02日 13:57:57 nicolelili1 阅读数:190   内存性能优化1.内存机制和原理 1.1 内存管理内存时一个基础又高深的话题,从 ...

  5. 1.2 Stream API

    引例: List<String> strList = Arrays.asList("zhaojigang","nana","tianya& ...

  6. ThreadLocal 简介 案例 源码分析 MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  7. ESLint 配置说明

    ESLint 有什么用,为什么要使用?   ESLint是一套可自定义规则的JS代码检查与修复工具 目标是保存团队代码的一致性和避免错误并且修复错误.减少团队沟通成本   "no-alert ...

  8. jstl 格式化

    一:JSTL格式化标签又称为I18N标签库,主要用来编写国际化的WEB应用,使用此功能可以对一个特定的语言请求做出合适的处理.例如:中国内地用户将显示简体中文,台湾地区则显示繁体中文,使用I18N格式 ...

  9. Oracle更改redo log的大小

    因为数据仓库ETL过程中,某个mapping的执行时间超过了一个小时, select event,count(*) fromv$session_wait group by event order by ...

  10. cProfile——Python性能分析工具

    Python自带了几个性能分析的模块:profile.cProfile和hotshot,使用方法基本都差不多,无非模块是纯Python还是用C写的.本文介绍cProfile.  例子 import t ...