SpringBoot------全局异常捕获和自定义异常

Posted 玉天恒

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot------全局异常捕获和自定义异常相关的知识,希望对你有一定的参考价值。

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------全局异常捕获和自定义异常的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot------全局异常捕获和自定义异常

SpringBoot配置全局异常捕获

springboot全局捕获异常

SpringBoot全局捕获异常示例

springboot编程之全局异常捕获

springboot 全局捕获异常