码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-10-11 23:55:52      阅读:34      评论:0      收藏:0      [点我收藏+]

标签:全局   private   object   workspace   project   地址   time   head   .com   

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格式的数据,
//可以使用@[email protected]替换@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------全局异常捕获和自定义异常

标签:全局   private   object   workspace   project   地址   time   head   .com   

原文地址:https://www.cnblogs.com/tianhengblogs/p/9775610.html

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!