前言

ControllerAdvice非常好用,可以把系统内部的异常统一处理。用起来也很简单。比如,http://www.cnblogs.com/woshimrf/p/spring-web-400.html

而Spring提供了一个base类ResponseEntityExceptionHandler,可以使用这个来处理。但用的时候要注意,不要重复定义异常捕获,对于base里已经定义好的,只要overwrite就好,不要重复声明异常拦截。

以下来自stackoverflow

问题


@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { private Logger log = LoggerFactory.getLogger(RestResponseEntityExceptionHandler.class); @Autowired
private ApplicationContext applicationContext; @ExceptionHandler({ ConstraintViolationException.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorWrapper handleConstraintViolationException(ConstraintViolationException e) {
String fieldName = e.getConstraintName();
String message = getResourceMessage(fieldName + ".alreadyExists", "Already Exists");
return new ErrorWrapper(fieldName + ".error", message);
} @ExceptionHandler({ MethodArgumentNotValidException.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorWrapper handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
return new ErrorWrapper(".error", "test");
} private String getResourceMessage(String key, String defaultMessage) {
String message = applicationContext.getMessage(key, null, Locale.getDefault());
if (StringUtils.isNotEmpty(message)) {
return message;
}
return defaultMessage;
}
}

将会得到以下异常:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped for [class org.springframework.web.bind.MethodArgumentNotValidException]: {public com.ca.bean.ErrorWrapper com.ca.exceptionHandler.RestResponseEntityExceptionHandler.handleMethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException), public final org.springframework.http.ResponseEntity org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(java.lang.Exception,org.springframework.web.context.request.WebRequest)}
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578) ~[spring-beans-4.3.0.RELEASE.jar:4.3.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-4.3.0.RELEASE.jar:4.3.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.3.0.RELEASE.jar:4.3.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.0.RELEASE.jar:4.3.0.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.0.RELEASE.jar:4.3.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.0.RELEASE.jar:4.3.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.0.RELEASE.jar:4.3.0.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:775) ~[spring-beans-4.3.0.RELEASE.jar:4.3.0.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861) ~[spring-context-4.3.0.RELEASE.jar:4.3.0.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) ~[spring-context-4.3.0.RELEASE.jar:4.3.0.RELEASE]
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444) ~[spring-web-4.3.0.RELEASE.jar:4.3.0.RELEASE]
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326) ~[spring-web-4.3.0.RELEASE.jar:4.3.0.RELEASE]
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107) [spring-web-4.3.0.RELEASE.jar:4.3.0.RELEASE]
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5099) [catalina.jar:7.0.70]
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5615) [catalina.jar:7.0.70]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147) [catalina.jar:7.0.70]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1571) [catalina.jar:7.0.70]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1561) [catalina.jar:7.0.70]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_92]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_92]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_92]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_92]
Caused by: java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped for [class org.springframework.web.bind.MethodArgumentNotValidException]: {public com.ca.bean.ErrorWrapper com.ca.exceptionHandler.RestResponseEntityExceptionHandler.handleMethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException), public final org.springframework.http.ResponseEntity org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(java.lang.Exception,org.springframework.web.context.request.WebRequest)}
at org.springframework.web.method.annotation.ExceptionHandlerMethodResolver.addExceptionMapping(ExceptionHandlerMethodResolver.java:109) ~[spring-web-4.3.0.RELEASE.jar:4.3.0.RELEASE]
at org.springframework.web.method.annotation.ExceptionHandlerMethodResolver.<init>(ExceptionHandlerMethodResolver.java:76) ~[spring-web-4.3.0.RELEASE.jar:4.3.0.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.initExceptionHandlerAdviceCache(ExceptionHandlerExceptionResolver.java:265) ~[spring-webmvc-4.3.0.RELEASE.jar:4.3.0.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.afterPropertiesSet(ExceptionHandlerExceptionResolver.java:241) ~[spring-webmvc-4.3.0.RELEASE.jar:4.3.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637) ~[spring-beans-4.3.0.RELEASE.jar:4.3.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) ~[spring-beans-4.3.0.RELEASE.jar:4.3.0.RELEASE]
... 21 common frames omitted

异常堆栈标明,重复定义了异常拦截。那么如果继承了ResponseEntityExceptionHandler之后,想修改某些内容怎么办呢?

答案

只要重写父类方法即可。不要在重写的方法上声明拦截异常。

对于ResponseEntityExceptionHandler已经定义好的异常,不需要重新定义,只要重写方法就可以了。

使用ControllerAdvice注意事项,Ambiguous @ExceptionHandler method mapped for [class org.springframework.web.bind.MethodArgumentNotValidException]的更多相关文章

  1. SpringBoot项目中的全局异常处理器 Failed to invoke @ExceptionHandler method

    文件下载代码 @RequestMapping(value = { "/data/docking/picture/{id}/{empi}" }) public JsonApi pic ...

  2. org.springframework.web.method.ControllerAdviceBean#isApplicableToBeanType 作用

    org.springframework.web.method.ControllerAdviceBean#isApplicableToBeanType(@Nullable Class<?> ...

  3. org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'PUT' not supported

    1:先上控制台报错信息 org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'PUT' not ...

  4. 添加@ControllerAdvice后报错 Failed to invoke @ExceptionHandler method

    首先.单独使用ControllerAdvice 无法正常工作.需要配合@EnableWebMvc 使用. @ControllerAdvice @EnableWebMvc pulbic class Ex ...

  5. Ambiguous handler methods mapped for HTTP path

    一.问题:映射重复导致的错误 java代码如下: @RequestMapping(value = "/info/{remove}/{id}", method = RequestMe ...

  6. Ambiguous HTTP method Actions require an explicit HttpMethod binding for Swagger 2.0

    异常内容 NotSupportedException: Ambiguous HTTP method for action . Actions require an explicit HttpMetho ...

  7. Ambiguous handler methods mapped for HTTP

    前端访问的 controller 地址没有加方法名导致找不到. Servlet.service() for servlet [spring] in context with path [/ssmDem ...

  8. 异常:java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path '/app/userInfoMaint/getProvince.do'

    调试代码时出现异常:java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path '/app/user ...

  9. org.springframework.web.method.HandlerMethod 与 org.springframework.messaging.handler.HandlerMethod 转换失败

    Springmvc hander.getclassclass org.springframework.web.method.HandlerMethod HandlerMethod.classclass ...

随机推荐

  1. Golang中的信号处理

    信号类型 个平台的信号定义或许有些不同.下面列出了POSIX中定义的信号. Linux 使用34-64信号用作实时系统中. 命令 man 7 signal 提供了官方的信号介绍. 在POSIX.1-1 ...

  2. 1267 - Illegal mix of collations (gbk_chinese_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '=' | 1267 - Illegal mix of collations (gbk_chinese_ci,IMPLICIT) and (Latin,COERCIBL)

    select * FROM information_schema.columns WHERE table_schema = "databaseName" and collation ...

  3. Weka学习 -- StringToWordVector 源代码学习(1)

    代码整个运行流程 參数设置 input数据,设置数据格式 batchFinished(),处理数据(Tokenzier,Stemming,Stopwords) determineDictionary( ...

  4. hdu 5078 Osu! (2014 acm 亚洲区域赛鞍山 I)

    题目链接:http://acm.hdu.edu.cn/showproblem.php? pid=5078 Osu! Time Limit: 2000/1000 MS (Java/Others)     ...

  5. Ration Rose2003安装及破解

    曾经学习UML的时候,用的是EA. 近期在看Head First想着画绘图装一下Ration Rose吧.于是就着手開始装.本来网上关于Ration Rose的安装及破解教程非常多,可是我在安装的过程 ...

  6. 【日常学习】【线性DP】codevs1044 拦截导弹题解

    题目描写叙述 Description 某国为了防御敌国的导弹突击,发展出一种导弹拦截系统.可是这样的导弹拦截系统有一个缺陷:尽管它的第一发炮弹可以到达随意的高度,可是以后每一发炮弹都不能高于前一发的高 ...

  7. 在Docker中运行asp.net core 跨平台应用程序

    概述 Docker已经热了有一两年了,而且我相信这不是一个昙花一现的技术,而是一个将深远影响我们日后开发和部署.运营应用系统的一种创新(很多人将其作为devops的一种非常重要的基石).学习docke ...

  8. 服务器固件测试--PCI设备的介绍(集成网卡和外插网卡)

    今天2017年9月26号,快三个月的时间,是该梳理一下,我来到这个岗位学到的东西. 网卡是什么 网卡分为俩大类 板载的集成网卡和外插的网卡.外插的网卡又分为很多种. 板载的集成网卡 外插的网卡分为 I ...

  9. 以KeyValue形式构建Lua Table

    Key为字符串 -- 定义一个key,value形式的table local kv = {fruit = "apple", bread = "french", ...

  10. java注解(转并做修改)

    本文由 ImportNew - 人晓 翻译自 idlebrains.欢迎加入翻译小组.转载请见文末要求. 自Java5.0版本引入注解之后,它就成为了Java平台中非常重要的一部分.开发过程中,我们也 ...