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格式的数据,
//可以使用@[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

另附:

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

时间: 2024-10-28 06:39:15

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

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

https://www.cnblogs.com/goloving/p/9142222.html 一.全局异常 1.首先创建异常处理包和类 2.使用@ControllerAdvice注解,全局捕获异常类,只要作用在@RequestMapping上,所有的异常都会被捕获 package com.example.demo.exception; import org.springframework.web.bind.annotation.ControllerAdvice; import org.spri

SpringBoot全局异常捕获

@ControllerAdvice //定义为切面拦截所有 public class GlobalExceptionHandler { @ExceptionHandler(RuntimeException.class) @ResponseBody // 拦截返回是 json返回结果 public Map<String, Object> exceptionHandler() { Map<String, Object> result=new HashMap<String, Obj

springboot编程之全局异常捕获

springboot编程之全局异常捕获 1.创建GlobalExceptionHandler.java,在类上注解@ControllerAdvice, 在方法上注解@ExceptionHandler(value = Exception.class),Exception.class表示拦截所有的异常信息 package com.imooc.web.controller; import com.imooc.exception.UserNotExistException; import org.spr

Spring-MVC开发之全局异常捕获全面解读(转)

异常,异常.我们一定要捕获一切该死的异常,宁可错杀一千也不能放过一个!产品上线后的异常更要命,一定要屏蔽错误内容,以免暴露敏感信息!在用Spring MVC开发WEB应用时捕获全局异常的方法基本有两种: WEB.XML,就是指定error-code和page到指定地址,这也是最传统和常见的做法 用Spring的全局异常捕获功能,这种相对可操作性更强一些,可根据自己的需要做一后善后处理,比如日志记录等. SO,本文列出Spring-MVC做WEB开发时常用全局异常捕获的几种解决方案抛砖引玉,互相没

Spring-MVC开发之全局异常捕获全面解读

在用Spring MVC开发WEB应用时捕获全局异常的方法基本有两种, WEB.XML,就是指定error-code和page到指定地址,这也是最传统和常见的做法 用Spring的全局异常捕获功能,这种相对可操作性更强一些,可根据自己的需要做一后善后处理,比如日志记录等. SO,本文列出Spring-MVC做WEB开发时常用全局异常捕获的几种解决方案抛砖引玉 互相没有依赖,每个都可单独使用! 定义服务器错误WEB.XML整合Spring MVC web.xml <error-page> <

spring boot2.0+中添加全局异常捕获

1.添加自定义异常,继承RuntimeException,为什么继承RuntimeException呢?是因为我们的事务在RuntimeException异常下会发生回滚. 1 public class BusinessException extends RuntimeException{ 2 3 public BusinessException(String code, String msg){ 4 this.code = code; 5 this.msg = msg; 6 } 7 8 pri

自定义全局异常捕获

原文:http://blog.csdn.net/jinzhencs/article/details/51700009 第一种:实现HandlerExceptionResolver 注意: 把错误码 重设成200,不然还是返回的异常信息. 注解@Compoment交由spring创建bean 之后就能愉快的返回自己的错误码了. 或者记录错误日志. /** * 全局异常捕获 * @author Mingchenchen * */ @Component public class GlobleExcep

MVC 好记星不如烂笔头之 ---&gt; 全局异常捕获以及ACTION捕获

public class BaseController : Controller { /// <summary> /// Called after the action method is invoked. /// </summary> /// <param name="filterContext">Information about the current request and action.</param> protected ov

C#中的那些全局异常捕获

1.WPF全局捕获异常 public partial class App : Application { public App() { // 在异常由应用程序引发但未进行处理时发生.主要指的是UI线程. this.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException); //  当某

Configure、中间件与ErrorHandlingMiddleware全局异常捕获

一.Configure Startup.cs中的Configure方法主要是http处理管道配置.中间件和一些系统配置,其中 IApplicationBuilder: 定义一个类,该类提供配置应用程序请求的机制管道.通过IApplicationBuilder下的run.use方法传入管道处理方法.这是最常用方法,对于一个真实环境的应用基本上都需要比如权限验证.跨域.异常处理等. IHostingEnvironment:提供有关正在运行的应用程序的web托管环境的信息 简单来说Configure方