SpringBoot 2.x 统一异常处理

Posted 琦4433

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot 2.x 统一异常处理相关的知识,希望对你有一定的参考价值。

1、统一异常处理类
package cn.hadron.controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
* 统一异常处理类
*/
@ControllerAdvice
public class GlobalExceptionHandler {

  /**
  * 返回的Map对象会被@ResponseBody注解转换为JSON数据返回
  * @return
  */
  @ExceptionHandler(Exception.class)
  @ResponseBody
  public Object handleException(HttpServletRequest request,Exception e){
    System.out.println("###出现异常!");
    Map<String,Object> map=new HashMap<>();
    map.put("url",request.getRequestURL().toString());
    map.put("msg",e.getMessage());
    return map;
  }
}


2、异常测试控制器
package cn.hadron.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class PathController extends BaseController{

  /**
  * 异常处理测试
  */
  @RequestMapping("/test")
  @ResponseBody
  public String test(String name) throws Exception{
    System.out.println("异常处理测试!");
    if(name==null) {
      throw new Exception("字段空值");
    }
    return "index";
  }

}

3、页面
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>错误页面</title>
<script type="application/javascript" th:href="@{js/jquery-2.2.3.min.js}"/>
<script type="application/javascript" th:href="@{bootstrap-table/js/bootstrap.min.js}"/>
<link rel="stylesheet" th:href="@{bootstrap-table/css/bootstrap.min.css}">
</head>
<body>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">异常信息</h3>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-4">
<div th:text="统一异常处理"></div>
<div th:text="@{url}"></div>
<div th:text="@{msg}"></div>
</div>
</div>
</div>
</body>
</html>

4、提醒
提醒,我们自定的@RequestMapping值不能为error,
比如

@RequestMapping("/error")
@ResponseBody
public String error(String name) throws Exception{
  System.out.println("异常处理测试!");
  if(name==null) {
    throw new Exception("字段空值");
  }
  return "index";
}

报异常如下,提示SpringBoot的org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error方法无法映射。

2019-03-05 14:08:40.286 WARN 11068 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘requestMappingHandlerMapping‘ defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map ‘basicErrorController‘ method
public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
to { /error}: There is already ‘pathController‘ bean method
public java.lang.String cn.hadron.controller.PathController.error(java.lang.String) throws java.lang.Exception mapped.
2019-03-05 14:08:40.286 INFO 11068 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService ‘applicationTaskExecutor‘
2019-03-05 14:08:40.290 INFO 11068 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2019-03-05 14:08:40.311 INFO 11068 --- [ main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with ‘debug‘ enabled.
2019-03-05 14:08:40.324 ERROR 11068 --- [ main] o.s.boot.SpringApplication : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘requestMappingHandlerMapping‘ defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map ‘basicErrorController‘ method
public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
to { /error}: There is already ‘pathController‘ bean method
public java.lang.String cn.hadron.controller.PathController.error(java.lang.String) throws java.lang.Exception mapped.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1745) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
at cn.hadron.DbApplication.main(DbApplication.java:23) [classes/:na]
Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map ‘basicErrorController‘ method
public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
to { /error}: There is already ‘pathController‘ bean method
public java.lang.String cn.hadron.controller.PathController.error(java.lang.String) throws java.lang.Exception mapped.
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.assertUniqueMethodMapping(AbstractHandlerMethodMapping.java:621) ~[spring-webmvc-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.register(AbstractHandlerMethodMapping.java:589) ~[spring-webmvc-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.registerHandlerMethod(AbstractHandlerMethodMapping.java:315) ~[spring-webmvc-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lambda$detectHandlerMethods$1(AbstractHandlerMethodMapping.java:282) ~[spring-webmvc-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at java.util.LinkedHashMap.forEach(LinkedHashMap.java:684) ~[na:1.8.0_181]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.detectHandlerMethods(AbstractHandlerMethodMapping.java:280) ~[spring-webmvc-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.processCandidateBean(AbstractHandlerMethodMapping.java:252) ~[spring-webmvc-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.initHandlerMethods(AbstractHandlerMethodMapping.java:211) ~[spring-webmvc-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.afterPropertiesSet(AbstractHandlerMethodMapping.java:199) ~[spring-webmvc-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.afterPropertiesSet(RequestMappingHandlerMapping.java:164) ~[spring-webmvc-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1741) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
... 16 common frames omitted


Process finished with exit code 1

以上是关于SpringBoot 2.x 统一异常处理的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot初始教程之统一异常处理

SpringBoot初始教程之统一异常处理

SpringBoot系列优雅的处理统一异常处理与统一结果返回

SpringBoot全局异常统一处理

SpringBoot全局异常统一处理

SpringBoot项目如何做到统一异常处理